简体   繁体   中英

ng2 component attributes confusion

I'm having a hard problems getting an Angular 2 component to work in an Angular 1 app. I'm successfully bootstrapping the app using ngUpgrade, and my component shows up as expected, but there's some weirdness going on with binding.

Here's a representation of the component as used inside another Angular 1 directive:

<stdbutton name="name-{{someId}}"
           (click)="doSomething()"
           [highlighted]="true"
           [size]="small">Clicky</stdbutton>

[highlighted] and [size] are both intended to be used as optional attributes on the element.

As you can see, I use both ng1 and ng2 style bindings. The ng1 binding works fine - output HTML will have name="name-12345" . The weirdness is in the ng2 bindings:

  • (click) doesn't execute the event handler
  • [highlighted] is in a weird state
  • [size] is always undefined

Here's the component definition:

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

@Component({
    selector: 'stdbutton',
    inputs: ['size', 'highlighted'],
    template: `
        <div [class]="buttonClass"
             [ngClass]="{stdbuttonhighlighted: highlighted}">
            <ng-content></ng-content>
        </div>
        `
})
export class StdButtonComponent {
    @Input() size: any;
    @Input() highlighted: boolean;

    buttonClass: string;

    constructor() {
        this.buttonClass = 'stdbutton' + (this.size ? this.size : '');
        console.log(this.highlighted);
        console.log(this);
    }
}

When I say that [highlighted] is in a weird state, here's what I mean. Look at the two console.log statements in the constructor. Now, the output:

stdbutton.component.ts:21 undefined

stdbutton.component.ts:22 
StdButtonComponent {buttonClass: "stdbutton"}
  buttonClass: "stdbutton"
  highlighted: true
  size: undefined

So, this.highlighted goes from undefined to true in between the two calls, and this.size remains undefined no matter what.

When you use [...] , you will try to evaluate an expression based on the properties of the component. If you want to set the string "value" you can use either:

  • [size]="'small'"
  • size="small"

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