ViewChild 裝飾器用於獲取模板視圖中的元素或直接調用其組件中的方法。它支持 Type 類型或 string 類型的選擇器,同時支持設置 read 查詢條件,以獲取不一樣類型的實例。好比ElementRef
和ViewContainerRef
.css
ViewChildren 裝飾器是用來從模板視圖中獲取匹配的多個元素,返回的結果是一個 QueryList 集合。segmentfault
@Component({ selector: 'app-child', template: '<p>{{name}}</p><div><input value="xixi"></div>', styleUrls: ['./child.component.css'] }) export class ChildComponent implements OnInit { public name: string = 'childName'; greeting(name: string) { console.log('hello ' + name); } }
@Component({ selector: 'app-root', template: `<app-child #childA></app-child> <app-child #childB></app-child> <button (click)="clickMe()" >點我</button>`, }) export class AppComponent implements OnInit { @ViewChild('childA') child1; @ViewChild(ChildComponent) child2; @ViewChild('childB', {read: ElementRef}) child3; @ViewChild('childB', {read: ViewContainerRef}) child4; @ViewChildren(ChildComponent) children; clickMe() { this.child1.greeting('child1'); this.child2.name = '我是child2'; this.child3.nativeElement.lastElementChild.firstElementChild.value = '我是child3~'; this.child4._data.componentView.component.greeting('child4'); this.children._results[0].greeting('children'); } }