Angular 2+ call a function in a child component from its parent component

前端 未结 3 1623
余生分开走
余生分开走 2020-12-28 12:06

I\'d like to know the best way to do this, and if there are different ways. I\'m trying to call a function in a child component from its parent component. So if I have:

3条回答
  •  时光说笑
    2020-12-28 12:47

    Well the other answers are just correct, but I think some times that function is supposed to be called with the flow of the data the angular way from parent to child, so what you actually need is to run a function every time a variable has changed in the parent component. see below:

    @Component({
      selector: "my-app",
      templateUrl: "./app.component.html",
      styleUrls: ["./app.component.css"]
    })
    export class AppComponent {
      name = "Angular";
      variable = "yes!";
      toggle() {
        this.variable = this.variable === "yes!" ? "hell no!" : "yes!";
      }
    }
    

    app tempalte:

    
    
    Parent says: {{variable}}    
    
    

    child component:

    export class ChildComponent implements OnInit {
      _childVar: string; // if you need to record the value and access later in child component
      counter = 0;
    
      @Input()
      set childVar(value: string) {
        this._childVar = value;
        this.childFunction(); // the answer is here
      }
    
      childFunction() {
        this.counter++;
        console.log("called child function");
      }
    
    }
    

    test here https://stackblitz.com/edit/angular-1rywfc

提交回复
热议问题