【问题标题】:Angular2 : Input bindingAngular2:输入绑定
【发布时间】:2017-03-23 03:15:54
【问题描述】:

我正在尝试将输入与此处定义的组件绑定:

https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child组件名称从未显示

我什至正在尝试执行 console.log,但它显示:

组件名称未定义

<div ng-switch="accessLevel">
<div class="customer" ng-switch-when="ENABLED">This is customer data</div>
<div class="customer-blurr"  ng-switch-when="DISABLED"> This is disabled Customer Data</div>
<div class="customer-blurr" ng-switch-default> <demo-error [componentName]="componentname"></demo-error></div>
</div>

error.html

<div> you are not allowed to access {{component}} </div>

演示错误:

import { Component, OnInit,Input } from '@angular/core';

@Component({
  selector: 'demo-error',
  templateUrl: './error.component.html',
  styleUrls: ['./error.component.css']
})
export class ErrorComponentDemo implements OnInit {
@Input() public componentName:string;
  constructor() { 
    console.log("componentName is" +this.componentName)
  }

  ngOnInit() {
  }

}

And in **CustomerComponent:**

@Component({
  selector: 'customer',
  templateUrl: './customer.component.html',
  styleUrls: ['./customer.component.css']
})
export class CustomerComponent extends SuperChildComponent{
  public allowed: boolean = false;
  public  accessLevel:AccessLevel =null;
  public componentname:string;

  constructor(private authenticationService : AuthorizationService) {
    super();
    this.componentname=this.constructor.name;
     this.accessLevel=this.authenticationService.isUserLoggedIn()?this.authenticationService.componentAccessLevel(this.constructor.name):null;
  }

我在这里错过了什么?

谢谢

【问题讨论】:

    标签: angular


    【解决方案1】:

    您的输入在构造函数中还不可用。试试这个 f.e.

    @Input set componentName(value: string) { 
      if(value != null && value != undefined) {
        this._componentName = value; console.log(this._componentName); 
      }
    }
    
    _componentName: string
    

    这样您就可以在set 内的if 语句中调用方法

    【讨论】:

      【解决方案2】:

      如果您的输入是字符串,则需要丢失“[]”。

      componentName="componentname"
      

      【讨论】:

        猜你喜欢
        • 2017-06-16
        • 2017-03-18
        • 2016-12-10
        • 2016-07-06
        • 2017-01-13
        • 1970-01-01
        • 2016-12-14
        • 2018-03-07
        • 2017-12-12
        相关资源
        最近更新 更多