2017-12-14 9 views
1

外部からコンポーネントにマークアップ/スタイリングを指定することはできますか?たとえば、次のコンポーネントでは、{{name}}をイタリックまたは太字にするにはどうすればよいですか?私はユーザーに好みのスタイルを決めるオプションを与えたいと思っています。外部からのコンポーネントのスタイリングを指定できますか?

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

@Component({ 
    selector: 'rio-child', 
    template: ` 
     Name is {{this.name}} <!-- user should specify whether name should be displayed in italic or bold --> 
    ` 
}) 
export class ChildComponent { 
    @Input() name:string; 
} 
+0

どのようにすることができ、それを囲むなしのタグと、あなたのスタイルのテキストコンテンツ? – Dummy

答えて

0

あなたは、あなたのコンポーネントに入力プロパティを追加span要素内のテキストを配置し、プロパティとスタイル、それが結合することができます:

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

@Component({ 
    selector: 'rio-child', 
    template: ` 
    Name is <span [style.font-weight]="isBoldName" [style.font-style]="isItalicName">{{name}}</span> 
    ` 
}) 
export class ChildComponent { 
    @Input() name:string; 
    @Input() isBold: boolean; 
    @Input() isItalic: boolean; 

    public get isBoldName(): string { 
    return this.isBold ? "bold" : "normal"; 
    } 

    public get isItalicName(): string { 
    return this.isItalic ? "italic" : "normal"; 
    }  
} 

プロパティは、マークアップ、このように設定されます。

<rio-child [name]="My name" [isBold]="true" [isItalic]="false"></rio-child> 

あなたはより多くをしたい場合この場合、

`Name is <span [ngStyle]="style">{{name}}</span>` 
@Input() style: any; 
<rio-child [name]="My name" [style]="{'font-weight': 'bold', 'color': 'green'}"></rio-child> 
0

:多彩なオプションは、1つのオブジェクト内のスタイル属性を設定し、そのプロパティにspan要素の[ngStyle]プロパティをバインドするために、入力プロパティを提供することができますあなたのユーザーはこのCSSを使用することができます

rio-child { 
    font-weight: bold; 
} 

しかし、より複雑なケースでは、ユーザー(::ng-deepの使用なし)コンポーネントのCSSをカスタマイズできるようにするには、あなたのコンポーネントがCSSのカプセル化

@Component({ 
    selector: 'rio-child', 
    template: '<...>', 
    encapsulation: ViewEncapsulation.None 
}) 

see doc here)を使用していけないことを指定する必要があり

関連する問題