这是我的父组件。当我单击此ag-grid-angular表中的一行时,它将把选定的行详细信息传递给子组件“ app-book-detail-reactive-form”。
<div class="jumbotron">
<div [hidden]="success">
<h1 class="display-4">Welcome!</h1>
<p class="lead">Manage your books here (Add, Edit etc)</p>
<button type="button" class="btn btn-primary" style="float: right;" (click)="goAddBook()"><span class="fas fa-plus-circle"></span> Add Book</button><br>
<hr class="my-4">
</div>
<ag-grid-angular #agGrid style="width: 100%; height: 350px;"
class="ag-bootstrap"
[gridOptions]="gridOptions"
[showToolPanel]="showToolPanel"
rowSelection="single"
(selectionChanged)="onSelectionChanged($event)"
(gridReady)="onGridReady($event)">
</ag-grid-angular>
<app-book-detail-reactive-form [book]="selectedBook"></app-book-detail-reactive-form>
</div>
这是我的子组件“ app-book-detail-reactive-form”,它将接受来自父组件的selectedBook值。发送的值采用
格式的数组[{
title: "harry potter",
description: "some cool stuff",
instance_list: [{...}, {...}]
}]
///
export class BookDetailReactiveFormComponent implements OnInit {
@Input() book: any[] = [{
title: '',
description: '',
instance_list: []
}];
constructor(
private modalService: NgbModal,
private fb: FormBuilder
) {}
ngOnInit() {
console.log(this.book);
this.bookDetailForm = this.fb.group(
{
title: [this.book[0].title, Validators.required],
description: [this.book[0].description],
instance_list: this.fb.array(this.book[0].instance_list)
}
)
}
}
这是我的反应式子组件的html
<div *ngIf="book" [hidden]="success">
<form [formGroup]='bookDetailForm' (ngSubmit)="onSubmit()" [hidden]="success">
<div class="form-group">
<div class="row">
<div class="col-sm-9">
<div class="form-group">
<label>Title of the Book</label>
<input type="text" class="form-control" placeholder="Title of Book" formControlName="title">
<div class="alert alert-danger" role="alert" *ngIf="titleAlert.invalid && titleAlert.touched">
Title of Book required!
</div>
</div>
<div class="form-group">
<label>Description of Book</label>
<textarea class="form-control" rows="3" placeholder="Enter Description of book..." formControlName="description"></textarea>
</div>
</div>
</div>
<hr class="my-4">
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>
我只想将从父组件中选择的值传递给子组件,并在可用时将这些所选值设置为子组件中的@input图书值。当然,@ input book的值在开始时为空。我尝试将其初始化为一些值,但仍然收到以下错误。
我收到错误消息“ AllBooksComponent.html:15错误TypeError:无法读取未定义的属性'0'”。
我该如何解决?
答案 0 :(得分:0)
也许很简单:
if(book !== null){
this.bookDetailForm = this.fb.group(
{
title: [this.book[0].title, Validators.required],
description: [this.book[0].description],
instance_list: this.fb.array(this.book[0].instance_list)
}
)
}
够吗?
答案 1 :(得分:0)
不使用ngInit,在输入中使用setter,请参见https://angular.io/guide/component-interaction#intercept-input-property-changes-with-a-setter
_book:any; //declare a variable _book
@Input()
set book(book:any){
this._book=book;
this.bookDetailForm = this.fb.group(
{
title: [book.title, Validators.required],
description: [book.description],
instance_list: this.fb.array(book.instance_list)
}
)
}
get book()
{
return this._book;
}