Подтвердить что ты не робот

Связывание с компонентом в angular2

Я хотел бы ссылаться на свойство на компоненте в A., что "конструктор компонента B. этот компонентный шаблон. Apis на этом, кажется, немного меняется, но я ожидаю, что следующее будет работать:

<my-component [greeting]="hello"></my-component>


// my component.es6.js
@Component({
  selector: 'my-component',
  properties: {
   'greeting': 'greeting'
  }
})
@View({
  template: '{{greeting}} world!'
})
class App {
  constructor() {
    console.log(this.properties) // just a guess
  }
}

Plunkr

Что я делаю неправильно?

4b9b3361

Ответ 1

Я экспериментировал с Angular2 и столкнулся с той же проблемой. Однако я нашел следующее для работы с текущей альфа-версией (2.0.0-alpha.21)

@Component({
  selector: 'hello',
  properties: {'name':'name'}
})
@View({
  template:`<h1>Hello {{_name}}</h1>`
})
class Hello {
  _name: string;

  constructor() { 
    console.log(this);
  };

  set name(name){
    this._name = name;
  }
}

@Component({
  selector: 'app',
})
@View({
  template:
  `
    <div>
      <hello name="Matt"></hello>
    </div>
  `,
  directives: [Hello]
})
class Application {
  constructor() { };
}

bootstrap(Application);

Похоже, что свойства класса, переданного в bootstrap, игнорируются. Не уверен, если это предназначено или ошибка.

Изменить: я только что построил Angular2 из исходного кода и попробовал аннотацию @Attribute, он работает в соответствии с документами (но только на вложенном компоненте).

constructor(@Attribute('name') name:string) { 
    console.log(name);
};

Отпечатает "Мэтт" на консоли.

Ответ 2

Текущий способ состоит в том, чтобы украсить свойство как @Input.

@Component({
    `enter code here`selector: 'bank-account',
    template: `
    Bank Name: {{bankName}}
    Account Id: {{id}}
    `
})
class BankAccount {
    @Input() bankName: string;
    @Input('account-id') id: string;
    // this property is not bound, and won't be automatically updated by Angular
    normalizedBankName: string;
}
@Component({
    selector: 'app',
    template: `
    <bank-account bank-name="RBC" account-id="4747"></bank-account>`,
    directives: [BankAccount]
})
class App {}
bootstrap(App);

выше пример из https://angular.io/docs/ts/latest/api/core/Input-var.html

Ответ 3

Собственно, вы можете сделать это лучше. Когда вы определяете свойства в своем компоненте, вы всегда указываете его следующим образом:

howYouReadInClass:howYouDefineInHtml

Итак, вы также можете сделать следующее:

@Component({
  selector: 'my-component',
  properties: {
   'greetingJS:greetingHTML'
  }
})
@View({
  template: '{{greeting}} world!'
})
class App {
set greetingJS(value){
this.greeting = value;
}
  constructor() {

  }
}

Таким образом, вы не получите конфликтов в TS, и у вас будет более четкий код - вы сможете определить переменную, как вы ее определяете в partent-компоненте.