gpt4 book ai didi

angular - 为什么 ContentChild 未定义?

转载 作者:行者123 更新时间:2023-12-02 03:57:37 25 4
gpt4 key购买 nike

我有两个组件 FormComponentTest1Component

Test1Component 使用 ng-content 显示 FormComponent

FormComponent.ts

import { Component, Input, Output, EventEmitter } from '@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 } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { FormComponent } from './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;
}
}

为什么 Test1Component.saveForm()this.contentChildForm 记录为 undefined

如何解决?

这是我做的plunker https://plnkr.co/edit/xbTgRuSd7nBIrOWsE1zO ,请打开控制台查看日志。

最佳答案

在您的情况下,我会使用@ViewChild,因为我在您的Test1Component中没有看到任何类型为FormComponent的可投影节点

<强> Modified Plunker

关于angular - 为什么 ContentChild 未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43278694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com