简体   繁体   中英

Can I use an angular component selector as an attribute for that component?

For example,

    @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>

My experience until now is that this doesn't work. Does anyone have any ideas on how to make this work? Or if it's even possible?

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

 [editor]="value"

it is possible, you should enclose your selector in square braces

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);
    }
}

then use like this

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM