![](/img/trans.png)
[英]Change-detection not working properly in ng2 component after navigation via angular1 ui-router
[英]ng2 component attributes confusion
我在使Angular 2組件在Angular 1應用程序中工作時遇到了難題。 我已使用ngUpgrade成功引導了應用程序,並且組件按預期顯示,但是綁定時有些奇怪。
這是在另一個Angular 1指令中使用的組件的表示形式:
<stdbutton name="name-{{someId}}"
(click)="doSomething()"
[highlighted]="true"
[size]="small">Clicky</stdbutton>
[highlighted]
和[size]
都打算用作元素上的可選屬性。
如您所見,我同時使用ng1和ng2樣式綁定。 ng1綁定可以正常工作-輸出的HTML將具有name="name-12345"
。 奇怪的是在ng2綁定中:
(click)
不執行事件處理程序 [highlighted]
處於怪異狀態 [size]
始終未定義 這是組件定義:
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);
}
}
當我說[highlighted]
處於怪異狀態時,這就是我的意思。 查看構造函數中的兩個console.log
語句。 現在,輸出:
stdbutton.component.ts:21 undefined
stdbutton.component.ts:22
StdButtonComponent {buttonClass: "stdbutton"}
buttonClass: "stdbutton"
highlighted: true
size: undefined
因此,在兩次調用之間, this.highlighted
從undefined
變為true
, this.size
, this.size
保持undefined
。
當您使用[...]
,您將嘗試根據組件的屬性評估表達式。 如果要設置字符串“ value”,則可以使用以下任一方法:
[size]="'small'"
size="small"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.