0

parent.html

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

parent.ts

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

children.ts

callHellotoConsole{
   this.sayhello()
}

How can i call sayhello() func from parent component ! I already call like that

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

children.ts

@Input() sayhello: Function;
Muhammet Can TONBUL
  • 3,217
  • 3
  • 25
  • 37
phutran
  • 19
  • 5
  • 1
    Possible duplicate of [Call child component method from parent class - Angular](https://stackoverflow.com/questions/38974896/call-child-component-method-from-parent-class-angular) – Kevin Nov 29 '19 at 11:05
  • @Kevin this is asking for the opposite interaction, how to call parent method from child – C.OG Nov 29 '19 at 11:23
  • you need to change your question. Call function from parent, is asking how to call a function from parent (what i said was a duplicate). call parent function from child is still a duplicate. https://stackoverflow.com/questions/43323272/angular-4-call-parent-method-in-a-child-component – Kevin Nov 29 '19 at 11:53

3 Answers3

1

I will suggest not trying to invoke the parent method in the child. Consider using an event emitter to communicate to the parent from the child https://angular.io/guide/component-interaction#parent-listens-for-child-event.

Parent Component:

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

Parent Component Template:

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

Child Component

@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
    }
}

When this.sayHello.emit(); is fired, your handler in your parent element (`onSayHello) will be called.

Here is a stackblitz demo

C.OG
  • 6,236
  • 3
  • 20
  • 38
1

Do not add braces '()' with 'sayHello' while passing it as an input value to the child component.

Try like this:-

Parent.ts

export class ParentComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  sayHello() {
    console.log('Hello');
  }

}

Parent.html

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

Child.ts

export class ChildComponent implements OnInit {

  constructor() { }

  @Input()
  sayHello: Function;

  ngOnInit() {
  }

  callHello() {
    this.sayHello();
  }

}
0

Try like this:

parent.ts

@ViewChild('childRef') child: ChildComponent;


child.sayhello()

.html

<children #childRef></children>
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79