天天看點

angular8 父子元件之間的通信 @ViewChild @Input

@ViewChild 在父元件中調用子元件

頭部元件用到新聞討論區件中

news

<app-header #header></app-header>
<button (click)="getChildClick()">
           

new.ts

import {ViewChild} from "@angular/core"
@ViewChild('header') header:any;
getChildClick(){
    this.header.run()
    var d = this.header.msg
}
           

header.ts

public msg:any='123'
run(){
    alert('111')
}
           

或 output EventEmitter 也可實作

子元件中引入   import {Output,EventEmitter} from "@angular/core"
@Output() outer = new EventEmitter()
this.outer.emit(''子元件資料)
父元件調用  <app-header (outer)="run($event)">
           

子元件接受資料

父元件調用子元件時傳入資料

<app-header [msg]='123' [run]="run" [home]="this"></app-header>
[home]="this"   home 傳入元件    this  目前元件
           

子元件引入接收

引入  import {Input} from "@angular/core" 
@Input()  msg:string;
@Input()  run:any;
@Input()  home:any;
{{msg}}
get(){
   this.run()
   this.home.msg
}