简体   繁体   English

Angular ngIF 不在组件内部工作

[英]Angular ngIF not Working inside component

i have a component called header but inside it my ngIf does not working and i have no idea why...我有一个名为 header 的组件,但在其中我的 ngIf 不起作用,我不知道为什么...

header.ts

  @Input() title: string;
  @Input() subTitle: string;
  @Input() isPage: string;

header.html标题.html

<header>

  <div>
   //this *ngif does not work, if its 'yes' it hide the element and if i set to 'no' still hide
    <ion-buttons *ngIf="isPage === 'yes' " slot="start" (click)="goBack()" style="margin-left: 0.5em;">
      <ion-button>
        <ion-icon name="chevron-back-outline"></ion-icon>
      </ion-button>
    </ion-buttons>

  </div>

  <div>
    // this work
    <h2>{{title}}</h2>
    <h1>{{subTitle}}</h1>
  </div>

</header>

otherComponent.ts其他组件.ts

<ion-content>
  <app-header title="lorum" subTitle="ipsum" isPage="yes" ></app-header>
</ion-content>

Why you use isPage as string?为什么你使用 isPage 作为字符串? it's better to use boolean最好使用布尔值

Then you code changed to然后你的代码改为

@Input() isPage: Boolean;

And

<ion-buttons *ngIf="isPage" slot="start" (click)="goBack()" style="margin-left: 0.5em;">

And

<app-header [title]="lorum" [subTitle]="ipsum" [isPage]="true" ></app-header>

You should make isPage boolean and pass the input like this您应该使isPage布尔值并像这样传递输入

<app-header [isPage]="true"></app-header>

I created a StackBlitz example我创建了一个StackBlitz示例

In your other component, you should assign the value of isPage to a variable, like this `const isPage = "yes";在你的另一个组件中,你应该将isPage的值isPage一个变量,像这样 `const isPage = "yes";

Then do this然后做这个

<app-header [title]="App" [subTitle]="header" [isPage]=isPage></app-header>

For anyone else who is having issues with this and the CommonModule solution above didn't apply to them.对于遇到此问题的任何其他人,上面的 CommonModule 解决方案不适用于他们。

I had the same issue because I created a new component with an embedded *ngIf inside of it running off of an internal class variable derived by logic inside of an ngOnChanges() method.我遇到了同样的问题,因为我创建了一个新组件,其中嵌入了*ngIf ,它运行了由ngOnChanges()方法内部的逻辑派生的内部类变量。 Nothing I did would allow the ngIf to function to not render the component.我所做的任何事情都不允许 ngIf 运行而不呈现组件。

What fixed it was I had to kill my ng serve and restart my angular dev server.修复它的是我不得不终止我的ng serve并重新启动我的 angular 开发服务器。 Once I did that the *ngIf started rendering correctly.一旦我这样做了*ngIf开始正确渲染。

¯_(ツ)_/¯ ¯_(ツ)_/¯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM