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;
3
  • 1
    Possible duplicate of Call child component method from parent class - Angular Commented Nov 29, 2019 at 11:05
  • @Kevin this is asking for the opposite interaction, how to call parent method from child Commented Nov 29, 2019 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. stackoverflow.com/questions/43323272/… Commented Nov 29, 2019 at 11:53

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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();
  }

}

Comments

0

Try like this:

parent.ts

@ViewChild('childRef') child: ChildComponent;


child.sayhello()

.html

<children #childRef></children>

2 Comments

in what file bro ??
parent.ts as you mentioned

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.