angular - Why ContentChild is undefined? -
i have 2 components formcomponent
, test1component
.
test1component
uses ng-content
display formcomponent
formcomponent.ts
import { component, input, output, eventemitter } '@angular/core'; @component({ selector: 'app-form', template:` <div class="panel panel-default fcs-form"> <div class="panel-header form-header"> {{headertitle}} </div> <div class="panel-body form-body"> <ng-content select="[form-body]"></ng-content> </div> <div class="panel-footer text-center form-footer"> <button class="btn btn-primary">{{resetbtntext}}</button> <button class="btn btn-primary" (click)="saveform()"> {{savebtntext}} </button> <button class="btn btn-primary">{{addbtntext}}</button> </div> </div> ` }) export class formcomponent{ @input() headertitle:string = "header title"; @input() savebtntext:string = "save"; @input() resetbtntext:string = "reset"; @input() addbtntext:string = "add"; @output() save:eventemitter<any> = new eventemitter(); constructor(){} saveform(e: any){ this.save.emit("save"); console.log("formcomponent save"); } }
test1component.ts
import { component, inject, oninit, contentchild } '@angular/core'; import { formgroup, formbuilder } '@angular/forms'; import { formcomponent } './form.component'; @component({ selector: 'app-test1', template: ` <app-form headertitle="my header" (save)="saveform(complexform.value, $event)"> <div form-body> <div class="jumbotron"> <form [formgroup]="complexform" (ngsubmit)="submitform(complexform.value)"> <div class="form-group"> <label>first name:</label> <input class="form-control" type="text" placeholder="john" [formcontrol]="complexform.controls['firstname']"> </div> </form> </div> </div> </app-form> ` }) export class test1component { @contentchild(formcomponent) contentchildform: formcomponent; complexform : formgroup; constructor(private fb: formbuilder){ this.complexform = fb.group({ 'firstname' : "", 'lastname': "", 'gender' : "female", 'hiking' : false, 'running' : false, 'swimming' : false }); } saveform(){ console.log(this.contentchildform); debugger; console.log("test1component save"); return true; } }
why test1component.saveform()
logging this.contentchildform
undefined
?
how fix ?
this plunker made https://plnkr.co/edit/xbtgrusd7nbirowse1zo , please open console see logs.
i use @viewchild
in case because don't see projectable nodes type formcomponent
in test1component
Comments
Post a Comment