首页 文章

Angular 2:ngIf在子组件内部不起作用

提问于
浏览
0

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

<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也无法正常工作,并且两个输入都没有出现!

请注意,此组件在另一个组件中使用 . 其中也使用了第三个组件 .

ReceivedPaymentsPage SubmitPaymentsComponent FormElemntValidationComponent

和.module文件声明:

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

})

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

2 回答

  • 0

    这可以做到请看看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'
        }
      }
    

    这会奏效

  • 0

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

相关问题