【问题标题】:Call function from parent angular从父角度调用函数
【发布时间】:2020-03-24 23:27:42
【问题描述】:

父.html

<p>parent</p>
<children></children>

父.ts

sayhello() {
   console.log("hello")
};

children.ts

callHellotoConsole{
   this.sayhello()
}

如何从父组件调用 sayhello() 函数! 我已经这样打电话了

  <children [sayhello] = "sayhello()"></children>

children.ts

@Input() sayhello: Function;

【问题讨论】:

标签: angular


【解决方案1】:

我建议不要尝试在子进程中调用父方法。考虑使用事件发射器从子https://angular.io/guide/component-interaction#parent-listens-for-child-event 与父通信。

父组件:

export class ParentComponent implements OnInit {
    .....
    onSayHello() {
        // Execute some code
    }
}

父组件模板:

<p>parent</p>
<children (sayHello)="onSayHello()"></children>

子组件

@Component({
   selector: 'child-component',
   templateUrl: './child-component.component.html',
   styleUrls: ['./child-component.component.scss']
})
export class ChildComponent implements OnInit {
    @Output() sayHello = new EventEmitter();
    .....
    sayHello() {
        this.sayHello.emit(); // you can send any variable to parent
    }
}

this.sayHello.emit(); 被触发时,您的父元素(`onSayHello)中的处理程序将被调用。

这是一个堆栈闪电战demo

【讨论】:

    【解决方案2】:

    在将“sayHello”作为输入值传递给子组件时,不要将大括号“()”添加到子组件中。

    试试这样:-

    父母.ts

    export class ParentComponent implements OnInit {
    
      constructor() { }
    
      ngOnInit() {
      }
    
      sayHello() {
        console.log('Hello');
      }
    
    }
    

    父.html

    <app-child [sayHello]="sayHello"></app-child>
    

    Child.ts

    export class ChildComponent implements OnInit {
    
      constructor() { }
    
      @Input()
      sayHello: Function;
    
      ngOnInit() {
      }
    
      callHello() {
        this.sayHello();
      }
    
    }
    

    【讨论】:

      【解决方案3】:

      试试这样:

      父.ts

      @ViewChild('childRef') child: ChildComponent;
      
      
      child.sayhello()
      

      .html

      <children #childRef></children>
      

      【讨论】:

      • 在什么文件中??
      • 你提到的parent.ts
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-30
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      相关资源
      最近更新 更多