如何防止Angular中if-else条件下组件的重构

问题描述 投票:1回答:2

我是ReactJS开发人员,刚进入Angular4俱乐部。我正在使用具有超简单条件的基本条件语句,如下所示:

<div class="app-component">

    <app-country *ngIf="condition"></app-country>         
    <app-country  *ngIf="!condition"></app-country> 
    <div>condition is [{{condition}}]</div>
    <button (click)="condition=!condition">Toggle condition</button>

</div>

这是我的app.component.ts文件。而其他app-country只是ng g创建的组件,只包含<p> hello country</p>。 App.component.ts中的条件每次都会切换。问题是当条件触发而不是重新渲染时,app-country会重新构造。例如,第一次条件从undefined变为true,然后app-country将被构造和渲染。第二次条件变为假,app-country被构造和渲染。但它应该重新渲染最后构造的组件。


我不知道这是一个问题,或者这是Angular的工作方式。我的观点是Angular有没有办法按照我希望的方式来解决这个问题?就像ReactJS中的keys告诉React这个组件键和React将其识别为组件实例的id一样。像这样

<AppCountry key='app-country'/>

任何帮助将不胜感激。谢谢

angular conditional
2个回答
1
投票

Vala Khosravi的答案是正确的,但只是为你解释。

NgIf指令是所谓的结构指令(如ngFor),这意味着它会更改模板。在ngIf的情况下,它从模板中删除组件或将其添加到模板化(基于条件)。如果从角度中删除模板中的组件,则将其销毁。

因此,您可以像Vala Khosravi所说的那样更改其visibility,或者如果您只想显示相同的组件但具有不同的数据,则可以使用Input。例如,带有配置数据的对象,只需根据条件更新输入。

因此,如果您希望根据条件显示不同的名称和标志,则有两个选项。 1.一个input,对象,名称和旗帜属性。这可以更容易使用,但是如果您需要检测输入中的更改,则angular不知道对象的属性已更改,因为它是相同的引用。简单的解决方法是以任何其他方式传播对象或创建新的引用。

<app-country [countryData]="countryData"></app-country>

在AppComponent中:

this.countryData = {
    name: 'Ukuleleland',
    flag: 'assets/images/ukuleleland.png',
};

在AppCountryComponent中:(输入需要从@ angular / core导入)

@Input() countryData;

并在模板中:

<div>
    <span>country name: {{countryData.name}}</span>
    <img [src]="countryData.flag">
</div>
  1. 同样的事情,但有两个输入:

你知道其余的。

还有一件事,我的小便:<div class="app-component">没有必要。你将拥有模板:

<app-component>
    <div class="app-component"></div>
    ...
</app-component>

如果您需要设置样式,可以使用:host() {display:block;}选择器。如果你需要动态地添加类或者什么,你可以使用@HostBinding

希望它有所帮助,角度好运。


2
投票

您可以使用隐藏属性而不是* ngIf并将您的代码更改为:

<div class="app-component">

    <app-country [hidden]="condition"></app-country>         
    <app-country  [hidden]="!condition"></app-country> 
    <div>condition is [{{condition}}]</div>
    <button (click)="condition=!condition">Toggle condition</button>

</div>

此属性将帮助您隐藏和显示您的dom而不触发构造函数

© www.soinside.com 2019 - 2024. All rights reserved.