Angular ngForm giving undefined



我试图使用ngOnInit获取值,并将表单初始化为默认值,但表单未定义。我也尝试过使用patchValue,但它不起作用,因为表单是未定义的。类似的代码在另一个组件中工作,但由于某种原因,这里的表单未定义。我对angular比较陌生,所以详细的解释会很有帮助。这是我的打字代码:

export class RecipeEditComponent implements OnInit {
@ViewChild("recipeForm",{static: false}) recipeForm: NgForm;
id: number;
recipe: Recipe;
editMode = false;
constructor(
private route: ActivatedRoute,
private recipeService: RecipeService
) {}
ngOnInit() {
this.route.params.subscribe((params: Params) => {
this.id = +params["id"];
this.recipe = this.recipeService.getRecipe(this.id);
this.editMode = params['id'] != null;
this.initForm()
});
}
initForm(){
if(this.editMode){
// this.recipeForm.setValue({
//   name: "abc",
//   imagePath: "abc",
//   description: "abc"
// })
console.log(this.recipeForm)
}
}
updateRecipeInfo(form: NgForm) {
// const newRecipe= new Recipe(values.name, values.imagePath, values.description, this.recipe.ingredients)
// this.recipeService.updateRecipe(this.id, this.recipe)
console.log(form)
}

}

这是我的html代码:

<form (ngSubmit)="updateRecipeInfo(recipeForm)" #recipeForm="ngForm">
<div class="form-group">
<label for="name">Name</label>
<input
id="name"
class="form-control"
name="name"
ngModel
required
/>
</div>
<div>
<label for="imagePath">Image URL</label>
<input
id="imagePath"
class="form-control"
name="imagePath"
ngModel
required
/>
</div>
<div>
<label for="description">Description</label>
<textarea
id="description"
class="form-control"
required
name="description"
ngModel
required
></textarea>
</div>
<div class="align-right-row">
<button type="submit" class="btn btn-info">Save</button>
<button type="button" class="btn btn-secondary">Cancel</button>
</div>
</form>

尝试将setValue包装在setTimeout中,如下所示。

initForm(){
if(this.editMode){
setTimeout(() => {
this.recipeForm.setValue({
name: "abc",
imagePath: "abc",
description: "abc"
})
console.log(this.recipeForm);
}, 0);
}
}

这将强制表单进入上下文,然后可以使用初始值设置值。

提交表单时应显示更改后键入表单的值。

这里,您从ngOnInit对recipeForm调用setValue,但对@ViewChild引用使用了选项{static:false}@使用{static:false}引用的ViewChild元素只能在AfterViewInit之后引用。这可能有助于:https://stackoverflow.com/a/57089572/15762779

如果它不在ngInInit((上工作,那么在ngAfterviewInit(((方法中使用它,如下所示。

试试这个

`@ViewChild('yourForm',{static:false}(yourForm:NgForm;

@ViewChildren('yourForm'(yourForm:NgForm;`

ngAfterviewInit() {
console.log(this.yourForm)

}

这将给你ngForm,你可以像valuchanges一样玩它,还有更多。

最新更新