It's not possible just to reference this: HomeComponent
and send data to HomeComponent
. Using this
,that
references belong to vanilla JS world, let's leave them there.
You have declared myFunction
takes in one param type of number. Why haven't you supplied a number in setTimeout()
? It can never work like that.
I don't see where is this.data
coming from, so I am going to assume what you want to achieve here is when components are sharing data.
I am going to create an example for you where child component HelloComponent
will send data to parent component AppComponent
. A) When you click button send data and B) like your example, with setTimeout()
delay.
We create a an event, that we emit from child and parent will catch the event and then show the data (string) carried by the event.
Child
@Component({
selector: 'hello',
template: `<h1><button (click)="sendMessage()">Send Message</button>`,
styles: [`h1 { font-family: Lato; }`],
})
export class HelloComponent {
message: string = 'Receiving Message from child';
@Output() messageEvent = new EventEmitter<string>();
ngOnInit(): void {
setInterval(
() => this.messageEvent.emit('hello, I am delayed meesage'),
5000
);
}
sendMessage() {
this.messageEvent.emit(this.message);
}
}
Parent
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
message:string='';
receiveMessage(sentMessage: string): void {
this.message = sentMessage;
}
}
{{message}}
<hello (messageEvent)="receiveMessage($event)"></hello>
Here is a working example: https://stackblitz.com/edit/angular-child-parent-1-s9q62k?file=src%2Fapp%2Fhello.component.ts
Here is more info how to use @Input/@Output decorators. https://angular.io/guide/inputs-outputs