Call a method of the child component

前端 未结 4 2002
执笔经年
执笔经年 2020-12-07 17:42

I have a nested child component like this:


    

         


        
4条回答
  •  执笔经年
    2020-12-07 17:47

    The best way to access a child component is @ViewChild.

    Let's say you have AppMainComponent with a nested ChildComponent from your example.

    // app-main.component.ts
    import { Component } from '@angular/core';
    
    @Component({
        selector: 'app-main',
        template: `
            
        `
    })
    
    export class AppMainComponent {}
    

    You want to invoke a clear method from your ChildComponent.

    // child.component.ts
    import { Component } from '@angular/core';
    
    @Component({
        selector: 'child-component',
        template: '{{ greeting }}'
    })
    
    class ChildComponent {
        greeting: String = 'Hello World!';
    
        clear() {
            this.greeting = null;
        }
    }
    

    You can accomplish it by importing the ChildComponent class, ViewChild decorator and pass component's class in it as a query. This way, you would have access to the ChildComponent's interface stored in the custom variable. Here is an example:

    // app-main.component.ts
    import { Component, ViewChild } from '@angular/core';
    import { ChildComponent } from './components/child/child.component';
    
    @Component({
        selector: 'app-main',
        template: `
            
        `
    })
    
    class ChildComponent {
        @ViewChild(ChildComponent)
        child: ChildComponent;
    
        clearChild() {
            this.child.clear();
        }
    }
    

    Notice! Child view becomes available only after ngAfterViewInit.

    Respond after Angular initializes the component's views and child views. Called once after the first ngAfterContentChecked(). A component-only hook.

    If you want to execute method automatically, you need to do it inside this lifecycle hook.

    You can also get a QueryList of child components via ViewChildren decorator.

    import { Component, ViewChildren, QueryList } from '@angular/core';
    import { ChildComponent } from './components/child/child.component';
    
    ...
    
    @ViewChildren(ChildComponent)
    children: QueryList;
    

    QueryList might be very useful, e.g. you can subscribe for children changes.

    It's also possible to create template reference variables and get access to them via the ViewChild decorator.

提交回复
热议问题