【问题标题】:Angular 2: ngIf not working inside a child componentAngular 2:ngIf 在子组件中不起作用
【发布时间】:2017-08-11 08:14:59
【问题描述】:

我正在创建一个有两个输入的组件,一个是数字,一个是文本,如下所示:

    <div class="form-group" *ngIf="inputType=='text'">
       <input class="form-control"  type="text" >
    </div>
    <div class="form-group" *ngIf="inputType=='number'">
        <input class="form-control"  type="number">
    </div>

.ts 文件:

@Component({
  selector: 'app-form-elemnt-validation',
  templateUrl: './form-elemnt-validation.component.html',
  styleUrls: ['./form-elemnt-validation.component.css']
})
export class FormElemntValidationComponent implements OnInit {

  constructor() { }
  inputType="text";
  ngOnInit() {

  }

}

但是ngIf 不起作用,即使将条件更改为 true 并且两个输入都不出现!!

请注意,该组件在另一个组件中使用。它也用于第三个组件。

ReceivedPayments 页面 提交付款组件 FormElementValidationComponent

和 .module 文件声明:

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes),
    SearchModule,
    FormsModule
  ],
  declarations: [
    ReceivedPaymentsPage,
    InvoiceShowDataComponent,
    ReceivedPaymentsTableComponent,
    SubmitPaymentsComponent,
    FormElemntValidationComponent
  ]

})

任何人都知道为什么ngIf 在这种情况下不起作用?

【问题讨论】:

  • 它按预期工作,问题可能出在其他位置?看到这个链接:plnkr.co/edit/KSWPYD3mhJgmdYJfwgH5?p=preview
  • 你在app.component.ts文件中导入FormsModule了吗?
  • 是 FormsModule 被导入到包含该组件声明的模块中
  • @Faisal ,我不知道为什么它在我的情况下不起作用,我认为这是一个微不足道的问题!
  • 我编辑了问题并添加了一些可能有助于理解问题的细节

标签: angular angular2-template


【解决方案1】:

这是可以做到的,请看Plunker link

JS

  @Component({
    selector: 'my-app',
    template: `
      <div>
        <h2>Hello {{name}}</h2>
        <cart></cart>
      </div>
    `,
  })
  export class App {
    name: string;
    constructor() {
      this.name = `Angular! v${VERSION.full}`
    }
  }

  @Component({
    selector: 'cart',
    template: ` <div class="form-group" *ngIf="inputType=='text'">
         <input class="form-control" placeholder='Text'  type="text" >
      </div>
      <div class="form-group" *ngIf="inputType=='number'">
          <input class="form-control" placeholder='Number'  type="number">
      </div><button (click)='changeText()'>change</button>`
  })

  export class Cart {
    inputType = 'text'
    construtor() {

    }
    changeText() {
      this.inputType = 'number'
    }
  }

这会起作用

【讨论】:

    【解决方案2】:

    您的问题似乎与您的组件模块结构有关, 我建议删除此组件并在与父级相同的目录中创建它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-04
      • 2019-10-10
      • 2018-06-24
      • 1970-01-01
      • 2020-10-22
      • 2017-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多