Issue
i am new to angular and trying to share data between pages on load of main page , i am using angular dynamic forms to create dynamic pages. my main page consist of child components pages that load in main page but when the data from my main page is passed to the child page using providers on page load the data reaches the child but doesnt store it in variable of child page
main page:
import { Component, Input, OnInit } from '@angular/core';
import { AppSelect } from '../component/multiselect.component';
@Component({
providers: [AppSelect], //child
selector: 'app-hello',
template: `<app-select></app-select>`,
styles: [`h1 { font-family: Lato; }`],
})
export class HelloComponent implements OnInit {
array: any[] = ['1', '2', '3', '4', '5', '6'];
constructor(private module: AppSelect //child) {}
ngOnInit() {
this.module.valuefrommainrpage(this.array); //value from here is sent to multiselect.component page
}
}
multiselect.component child page :
import { Component, VERSION } from '@angular/core';
@Component({
selector: 'app-select',
template: `
<select multiple="multiple" name="" id="" style="width:300px;height:300px;">
<option *ngFor="let items of module" [value]="items">{{items}}</option>
</select>
<br>
<button (click)="setvalue()">CLICK</button>
<button
(click)="console()">consolevalues</button>`,
styles: [`h1 { font-family: Lato; }`],
})
export class AppSelect {
module: string[] = [];
setvalue() {
this.module = ['one', 'two', 'three', 'four', 'five'];
}
valuefrommainrpage(data) {
//data is recievd from main page on ngOnInit of mainpage
console.log(data);
this.module = data; //data should be set here but doesnt
}
console() {
console.log(this.module);
}
}
my stackblitz code : Sharing data from main to child component
i dont understand how this is happening as i am receiving data from main page but cannot store it in variable
Solution
A common pattern in Angular is sharing data between a parent component and one or more child components. Implement this pattern with the @Input() and @Output() decorators.
Sending data to a child component
It is necessary to create a variable with @Input()
decorator:
@Input() item = ''; // decorate the property with @Input()
and in parent component set value to this variable:
<app-detail-component [item]="anItem"></app-detail-component>
Answered By - StepUp
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.