我可以使用角度组件选择器作为该组件的属性吗?

时间:2017-06-14 13:56:04

标签: javascript angular data-binding angular-components

例如,

    @Component({
      selector: 'editor', //Same as component input
      templateUrl: './editor.component.html',
      styleUrls: ['./editor.component.scss']
    })
    export class Editor implements OnInit {
      @Input() editor: string; //Same name as selector
      @Input() color: string;
      constructor() { }

      ngOnInit() {
      }
   }

HTML: <div editor="value" color="blue"></div>

直到现在我的经验是,这不起作用。有没有人对如何使这项工作有任何想法?或者,如果它甚至可能?

2 个答案:

答案 0 :(得分:0)

您应该在div标签上使用属性绑定。

componentWillReceiveProps(nextPropsFromRedux) {
  this.setState({ somethingFrom: nextPropsFromRedux.property})
}

答案 1 :(得分:0)

有可能,您应该将选择器用方括号括起来

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

@Component({
    selector: '[editor]', //Same as component input
    template: `<span>Foo Bar template</span>`,
})
export class TryComponent implements OnInit {
    @Input() editor: string; //Same name as selector
    @Input() color: string;
    constructor() { }

    ngOnInit() {
        console.info(this.editor);
    }
}

然后像这样使用

<div [editor]="'FooBarValue'" color="blue"></div>

<div [editor]="classProperty" color="blue"></div>