I'm developing a little tool where I need to populate a variable on component creation. I've declared variable here:
export class HomeComponent implements OnInit {
myVar: any
and try to set its value here:
ngOnInit(): void {
setInterval(() => this.myFunction(), 3000);
}
myFunction(arg: number): void {
this.data.forEach(function (this: HomeComponent, element: any) {
if (element.id === number) {
this.myVar = element.id;
}
});
}
but no value was passed and I get this error: "ERROR TypeError: this is undefined"
Any idea? Thank you in advice!
CodePudding user response:
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/app/hello.component.ts
Here is more info how to use @Input/@Output decorators. https://angular.io/guide/inputs-outputs
CodePudding user response:
Arrow functions do not have their own 'this'. Arrow functions establish "this" based on the scope the Arrow function is defined within.
Try to change the code like below by just sending the myFunction as reference
setInterval(myFunction, 3000);
