这是我的孩子部分
子html//add-child.component.html
<div class="content">
<h6 class="title" translate>
<span *ngIf="addTitle" translate>Add</span>
<span *ngIf="editTitle" translate>Edit</span>
</h6>
<div class="row">
<form [formGroup]="administrationForm">
<input type="text" class="form-control form-control-sm"
formControlName="adminId"
</form>
</div>
</div>
子组件...
@Component({
selector: 'app-add-hospital',
templateUrl: './add-child.component.html'
})
export class AddChildComponent implements OnInit {
addTitle = true;
editTitle = false;
}
Parent component.html
<button (click)="enableChild()"></button>
<app-add-child #newChild></app-add-child>
父组件
@Component({
selector: 'app-hospitals',
templateUrl: './parent.component.html'
})
export class ParentComponent implements OnInit {
@ViewChild(AddChildComponent , { static: true }) newChild: AddChildComponent ;
@ViewChild(AddChildComponent , { static: true }) set Content(newChildRef) {
this.newChild = newChildRef;
}
constructor(){}
enableChild() {
// this.add = true;
this.newChild.addTitle = false;
this.newChild.editTitle = true;
this.loadById(event);
}
loadHospitalById() {
//server call
this.hospitalService.getById().subscribe(response => {
this.newChild.administrationForm.patchValue({
adminId: result["adminId"]
})
}
}
[加载父级时,它加载子级。在父页面的末尾会导致很多空白。我仅在调用Enable child方法时才需要加载子DOM。我尝试在加载子项时在父项中添加ngIf,但这会导致初始化问题,需要使用某些子项值。
仅在需要时如何加载子项。(ng如果无法工作,因为启用时我需要子项引用)
据我从您的代码中可以看到的,您希望将状态从父级传递到子级,并以一种非常曲折的方式进行。您只需要简单的property-binding。
我将从如下更改子组件开始;
@Component({
selector: 'app-add-hospital',
templateUrl: './add-child.component.html'
})
export class AddChildComponent implements OnInit {
@Input addTitle = true;
@Input editTitle = false;
}
然后摆脱对父组件的曲折视图查询;
@Component({
selector: 'app-hospitals',
templateUrl: './parent.component.html'
})
export class ParentComponent implements OnInit {
enableChild = false;
addTitle: boolean;
editTitle: boolean;
constructor(){}
enableChild() {
this.enableChild = true;
this.addTitle = false;
this.editTitle = true;
}
}
最后;
<button (click)="enableChild()"></button>
<app-add-child *ngIf="enableChild" [addTitle]="addTitle" [editTitle]="editTitle"></app-add-child>
您可以在*ngIf
组件内部使用app-add-child
属性,因此该组件有效,但是所有条目都被删除了
//app-data-child-content
<div class="content" *ngIf="show">
<h6 class="title" translate>
<span *ngIf="addTitle" translate>Add</span>
<span *ngIf="editTitle" translate>Edit</span>
</h6>
<div class="row">
<!-- form -->
</div>
</div>
...
class ChildAddComponent{
@Input()
show=false;
}
///parent-component
<button (click)="enableChild()"></button>
<app-add-child [show]="showChild" #newChild></app-add-child>
...
class ParentComponent{
showChild=false;
enableChild() {
this.showChild=true;
this.enableChild = true;
this.addTitle = false;
this.editTitle = true;
}
}