網站搜尋

typescript - 如何在 Angular 2 中讀取組件輸入屬性綁定的字串值?


我在我的 Angular2 應用程式中有一個簡單的表單輸入元件,其中包含一個 @Input 綁定到屬性 [dataProperty]。正如你可能猜到的,[dataProperty] 屬性是一個格式為 [dataProperty]="modelObject.childObj.prop" 的字串值,其中 modelObject 是在我的應用程式中共享的模型。基本上,我使用這個 @Input 屬性將模型從父元件傳遞給我的 <custom-text-input> 元件,然後它會通過 [ngModel] 綁定到嵌套元件的輸入。

一切都如預期般運作,在我的控制器中也是如此;即當我存取 this.dataProperty 時,會返回與輸入綁定的模型上的值。然而,我似乎無法弄清楚的是,如何從模板中首次存取傳遞給 [dataProperty] 的字串文字。

元件:

@Component{
    selector: "custom-text-input",
    template: "<input type="text" [ngModel]="dataProperty"></input>
}

export Class customInputComponent implements OnInit {
    @Input() dataProperty: string;

    /**
       ex of modelObject: { detail: { name: "Cornelius" } }
       (^^^ would originate in parent component ^^^)
    */

    constructor() {}

}

使用案例:

<div class=wrapper>
    <custom-text-input [dataProperty]="modelObject.detail.name">
    </custom-text-input>
</div>

基本上,當我從組件控制器訪問 this.DataProperty 時,它返回的是「Cornelius」。是否有可能訪問字串文字,以便我也可以從控制器捕獲 "modelObject.detail.name" 這個字串?

答案#1

我會創建一個屬性及其名稱的鍵值對,並像這樣一起傳遞它們:

<div class="wrapper">
    <custom-text-input [dataProperty]="{modelObject.detail.name}">
    </custom-text-input>
</div>

然後我可以透過像這樣的方式來訪問屬性名稱:

@Component{
    selector: "custom-text-input",
    template: "<input type="text" [ngModel]="dataProperty"></input>
}
export Class customInputComponent {

    dataPropertyName;

    private _dataProperty;    
    @Input() 
    set dataProperty( keyValuePair ){
      this._dataProperty = Object.values(keyValuePair)[0]
      this.dataPropertyName = Object.keys(keyValuePair)[0]
    }
    get dataProperty( ){
      console.log( "I have the property name here:" + this.dataPropertyName )
      return this._dataProperty
    }

}

希望這對你有幫助!

答案#2

從技術上講,這應該是可能的。但你必須有些跳出框架思考。帶有 dataProperty 的元素,最終只是個 HTML 節點。

<custom-text-input [dataProperty]="modelObject.detail.name">

我目前沒有能力為你創建一個示例,但你可以簡單地獲取組件的 HTML 參考(在你的組件中使用 Angular 的 viewReference),然後簡單地查詢它的屬性。偽代碼可能類似於

 let myString = viewref.nativeElement.getAttribute('[dataProperty]')

再說一次,我還沒測試過,但我看不出有什麼理由它不會奏效。