2016-02-19 10 views
5

मैं कोणीय 2 में एक बटन घटक बनाने की कोशिश कर रहा हूं। होस्ट पर मुझे गतिशील रूप से जेनरेट किए गए सीएसएस क्लासनाम को सेट करना होगा। (बाध्य संपत्ति के आधार पर)देशीElement.classList.add() वैकल्पिक

होस्ट पर '[ngClass]' काम नहीं करता है।

मैं पढ़ा है कि elementRef.nativeElement.classList.add (मान) का उपयोग करते हुए, क्योंकि classList webworkers (या तो)

क्या मेरे सबसे अच्छे विकल्प उत्पन्न करने के लिए कर रहे हैं पर समर्थित नहीं है, सबसे अच्छा तरीका है या तो नहीं है क्लास गतिशील रूप से मेजबान पर?

@Component({ 
    selector: '[md-button]', 
}) 
export class MdButton { 
    color_: string; 

    @Input 
    set color() { 
     this.color_ = value; 
     if (this.elementRef !== undefined) { 
      this.elementRef.nativeElement.classList.add('md-' + this.color_); 
     } 
    } 

    get color(): string { 
     return this.color_; 
    } 

    constructor(public elementRef: ElementRef){} 
} 
+1

'this.elementRef.nativeElement.className + = 'md-' + this.color_'? – dfsq

उत्तर

7
@Component({ 
    selector: '[md-button]' //, 
    // host: { '[class]': 'classList()' } 
}) 
export class MdButton { 
    color_: string; 

    // classList() { 
    // return 'md-' + this.color_; 
    // } 

    @Input 
    set color() { 
     this.color_ = value; 
     // if (this.elementRef !== undefined) { 
     // this.elementRef.nativeElement.classList.add('md-' + this.color_); 
     // } 

     this.renderer.setElementClass(this.elementRef, 'md-' + this.color_, true); 
    } 

    get color(): string { 
     return this.color_; 
    } 

    constructor(public elementRef: ElementRef, private renderer: Renderer2){} 
} 
+0

धन्यवाद @ günter-zöchbauer, लेकिन यह एक समस्या छोड़ देता है। जब '<बटन md-button class = "myCustomClass" color = "accent" सेट करने का प्रयास करें,' कक्षा 'myCustomClass' को 'md-accent' द्वारा ओवरराइड किया गया है। दोनों मौजूद होना चाहिए। – BakGat

+0

मैंने अपना जवाब अपडेट किया। मुझे पूरी तरह से यकीन नहीं है कि 'elementRef' या 'elementRef.nativeElement' को पारित करने की आवश्यकता है या नहीं। हाल ही में अपडेट किए गए यह कुछ/सभी एपीआई के लिए बदला गया था और मैंने जांच नहीं की है क्योंकि 'रेंडरर' शामिल है लेकिन मुझे ऐसा लगता है। –

+0

धन्यवाद, मैं आज बाद में कोशिश करूंगा। – BakGat

3

धन्यवाद गुंटर को मैं समाधान मिल गया है। यह उसका कोड है लेकिन भविष्य में इसका उपयोग करने वाले किसी भी व्यक्ति के लिए साफ़ किया जा सकता है।

private color_: string; 

@Input() 
set color(value: string) { 
    this.color_ = value; 

    this.renderer.setElementClass(this.elementRef, 'md-' + this.color_, true); 
} 

get color(): string { 
    return this.color_; 
} 

constructor(private elementRef: ElementRef, private renderer: Renderer) { } 
संबंधित मुद्दे