我有一个称为取消的组件,当用户单击名称组件中的按钮时,我想调用该组件。我通过在调用“搜索”按钮时将loadCancellation标志设置为true来实现。然后在取消组件中,如果loadCancellation设置为true,则仅显示html。
但是,在开发人员工具中,在加载名称组件以及单击“搜索”按钮时,将首先调用取消组件。
如何防止在加载名称组件时调用取消组件?
我尝试在名称组件构造函数中将loadCancellation标志设置为false。但是取消组件仍然被提出。
我认为这是因为我将loadCancellation设置为组件的属性,如下所示。
<app-cancellation [zipCode]="zipCodeVal" [lastName]="lastNameVal" [loadCancellation]="loadCancellation"></app-cancellation>
代码如下:
names.component.html
<form class="body">
<mat-form-field>
<textarea [(ngModel)]="zipCodeVal" matInput placeholder="ZipCode" name="zipCode"></textarea>
</mat-form-field>
<mat-form-field>
<textarea [(ngModel)]="lastNameVal" matInput placeholder="LastName" name="lastName"></textarea>
</mat-form-field>
<button mat-raised-button color="primary" (click)="onSearch()">Search</button>
</form>
<app-cancellation [zipCode]="zipCodeVal" [lastName]="lastNameVal" [loadCancellation]="loadCancellation"></app-cancellation>
names.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-names',
templateUrl: './names.component.html',
styleUrls: ['./names.component.css']
})
export class NamesComponent {
private zipCode: string;
private loadCancellation: boolean;
constructor() {
// this.loadCancellation = false;
}
onSearch() {
this.loadCancellation = true;
console.log("cancellation is: " + this.loadCancellation);
}
}
cancellation.component.html
<div *ngIf="loadCancellation">
<p>
ZipCode is: {{zipCode}} lastName is: {{lastName}}
</p>
</div>
cancellation.component.ts
import { Component, Input, AfterViewInit } from '@angular/core';
import { CustomerNameService } from '../customer-name.service';
import { CustomerName } from '../customer-name';
@Component({
selector: 'app-cancellation',
templateUrl: './cancellation.component.html',
styleUrls: ['./cancellation.component.css']
})
export class CancellationComponent implements AfterViewInit {
@Input('zipCode') zipCode: string;
@Input('lastName') lastName: string;
@Input('loadCancellation')
set loadCancellation(loadCancellation: boolean) {
console.log("inside set cancellation");
this.customerNameService
.getCustomerNames(this.zipCode, this.lastName)
.subscribe(data => {this.customerNames = data;})
}
customerNames: Array<CustomerName>
constructor (private customerNameService: CustomerNameService) {
}
ngAfterViewInit() {
// console.log(this.loadCancellation);
}
}
答案 0 :(得分:2)
如果组件选择器存在于html模板中,则将创建它。创建时,将传递输入值(此处为true和false只是值),并且将运行ngOnInit()
。
如果只希望在loadCancellation
为true时创建取消组件,则可以执行以下操作。
<app-cancellation *ngIf="loadCancellation" [zipCode]="zipCodeVal" [lastName]="lastNameVal"></app-cancellation>
祝你好运!