模版在组件类中的引用:@ViewChild与@ViewChildren的使用

85 阅读1分钟

1.@ViewChild的使用

<childHtml #helloDiv> // 给html标签添加一个标记“#xxx..”,这个标记就是给模版或者DOM元素起一个引用名字,以便在组件类或模版中进行引用,如父组件要调用子组件的方法时,就给子组件添加一个这种标记
    你好
<childHtml>
export class ParentComponent {
    @ViewChild('helloDiv', {static: false}) childComponent: ChildComponent;
    // static:指我们引用的组件是否在*ngIf/*ngFor之下,如果是,那么就是动态的,static值为false
    function someFunc() {
        //父组件调用子组件的方法,或改变子组件的属性值
        this.childComponent.someChildFunc();
    }
}

2.@ViewChildren的使用:引用多个模版

<img
    #img
    *ngFor="let slider of sliders"
    [src]="slider.imgUrl"
    [alt]="slider.caption"
/>

@ViewChildren('img') imgs: QueryList<ElementRef>
// ElementRef是Angular中的dom元素的包装类