Reputation: 925
I have this plunker:
https://plnkr.co/edit/5XbuxoGG6NqomayLP4Ae?p=preview
I have this:
> @Component({ selector: 'my-app', template: `
> <layout [child]="childModal">
> <div class="body">
> <common-modal #childModal [title]="'common modal'">
> <div class="modal-body">
> {{5+7}} {{item}}
> Hi heloo </div>
> </common-modal>
> </div>
> </layout>
> <button type="button" class="btn btn-primary" (click)="childModal.show()">Open modal</button>
>
>
> `, })
export class AppComponent {
@ViewChild('childModal') childModal :CommonModalComponent;
item:number=150;
constructor(private viewContainerRef: ViewContainerRef) {
}
}
How in layout commponent i can set item from App component. Any suggestion? My question is how to set child variable from parent if i dont have in child only parent component and some other components.
<parent>
<some-other-component></some-other-component>
</parent>
I dont have selector for child. How can i change in layout component value of item that is in AppComponent?
EDIT: This is what im trying to do: https://plnkr.co/edit/BVS2AlQNZ7kO5wbsTBaA?p=preview
But emit is not working for some reason.
Upvotes: 1
Views: 425
Reputation: 81
You need to create an input variable to the item inside the layout component and an output variable to emit an event to your app component handle it and change the value of your item variable.
AppComponent:
@Component({
selector: 'my-app',
template: `
<layout [child]="childModal" [item]="item" (itemChange)="onItemChange($event)">
<div class="body">
<common-modal #childModal [title]="'common modal'">
<div class="modal-body">
{{5+7}} {{item}}
Hi heloo
</div>
</common-modal>
</div>
</layout>
<button type="button" class="btn btn-primary" (click)="childModal.show()">Open modal</button>
`,
})
export class AppComponent {
@ViewChild('childModal') childModal :CommonModalComponent;
item:number=150;
constructor(private viewContainerRef: ViewContainerRef) {
}
onItemChange(item) {
this.item = item;
}
}
Layout:
import {Component,Input, Output, ViewChild, EventEmitter} from '@angular/core';
import { ModalDirective } from 'ng2-bootstrap/ng2-bootstrap';
@Component({
selector: 'layout',
template: `
<div class="modal-body">
<button (click)="show()">CLICKKK</button>
<ng-content select="div.body"></ng-content>
</div>
`,
})
export class Layout {
@Input() title?:string;
@Input() child;
@Input() item;
@Output() itemChange: EventEmitter = new EventEmitter;
constructor() {
}
show() {
this.item = 200;
this.child.show();
this.itemChange.emit(this.item);
}
}
EDIT: I think you haven't understood my answer... so take a look at this link: https://plnkr.co/edit/mFcoiXqFedN1RO7tsETX?p=preview
I coded it and added some comments to explain.
Upvotes: 0