import { Component, OnInit, ViewChild } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
constructor() { }
ngOnInit() {
}
greeting(str: string) {
console.log(str);
}
}
<p>
child works!
</p>
<app-child #child1></app-child>
<app-child #child2></app-child>
<button (click)="child2.greeting('child2的问候')">点我</button>
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child/child.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
@ViewChild('child1')
child1: ChildComponent;
constructor() {
}
// tslint:disable-next-line:use-life-cycle-interface
ngOnInit(): void {
this.child1.greeting('child1的问候');
}
}