美文网首页
2018-10-12

2018-10-12

作者: 标准函数库 | 来源:发表于2018-10-12 22:44 被阅读1次

    昨天一个同事觉得页面上的 搜索框不好看,让我抽成一个组件,想了一下就写个简单的搜索框加按钮的组合,然后觉得这个output用的不多,可以总结一下。

    当我们想要实现子组件向父组件传递值时,就要用到output装饰器了。在搜索组件内写好了搜索handle函数,但是处理逻辑又是在父组件里定义的,这时候就要像下面这样

    searchBtn.component.html

    <div>
    
          <button (click)="handleSearch()">搜索
    
             <span class="glyphicon glyphicon-search"></span></button>
    
          <input [(ngModel)]="keyword" (keyup.enter)="handleSearch()">
    
    </div>
    
    

    searchBtn.component.ts

    
    import { Component, OnInit, Output, EventEmitter} from '@angular/core';
    
    @Component({
    
      selector: 'search-btn',
    
      templateUrl: './search-btn.component.html',
    
      styleUrls: ['./search-btn.component.css']
    
    })
    
    export class SearchBtnComponent implements OnInit {
    
      @Output() searchEvent: EventEmitter<any> = new EventEmitter()
    
      constructor() { }
    
      keyword: string;
    
      ngOnInit() {
    
        this.keyword = '';
    
      }
    
      handleSearch(){
    
        this.searchEvent.emit(this.keyword)
    
      }
    
    }
    
    

    这里面的关键就是EventEmitter,它能够触发自定义事件。关于这个对象,修仙之路里是这样描述的:子指令创建一个 EventEmitter 实例,并将其作为输出属性导出。子指令调用已创建的 EventEmitter 实例中的 emit(payload) 方法来触发一个事件,父指令通过事件绑定 (eventName) 的方式监听该事件,并通过 $event 对象来获取 payload 对象。

    在上面的代码里就是,子组件创建了searchEvent,并将其输出。在handleSearch方法里触发他并将输入框的值传递出去,这样在父组件就可以在对searchEvent事件绑定处理函数了

    app.component.html

    <search-btn (searchEvent)="dosth($event)"></search-btn>

    app.component.ts

    
    @Component({
    
      selector: "app-root",
    
      templateUrl: "./app.component.html",
    
      styleUrls: ["./app.component.css"]
    
    })
    
    export class AppComponent {
    
      constructor(private http: HttpClient) {}
    
    ngOnInit() {  }
    
      dosth(value){
    
        console.log(value);
    
      }
    
    }
    
    

    相关文章

      网友评论

          本文标题:2018-10-12

          本文链接:https://www.haomeiwen.com/subject/eejnaftx.html