2016-09-20 10 views
0

Ionic 2 애플리케이션에서 각도 2를 사용하고 있습니다. 내 구성 요소에서 사용할 템플릿에서 가치를 얻고 싶습니다. 내 구성 요소에서 변수를 정의한 다음 내 템플릿에서 변수를 사용하는 방법을 알고 있지만 다른 방법을 찾고 있습니다. 여기의 의미는 다음과 같습니다각도 2 템플릿에서 구성 요소 변수를 가져옵니다.

구성 요소 :

@Component({ 
    template: '<ion-list [route]="path/on/site"> 
       <ion-item *ngFor="let item of items"> 
        {{title}} 
       </ion-item> 
      </ion-list>' 
}) 
export class List { 
    route: string; 

    constructor() { 

    this.route = // should get value of [route] in template; 
    this.loadData(this.route); 

    } 

    loadData()... 

} 

내가 템플릿 [경로]의 값을 하드 코딩 한 다음 this.route로 내 구성 요소에 그 값을 얻을합니다. [경로]는 이온 목록에있을 필요는 없습니다. 구성 요소에 넣을 수있는 한 아무 곳이나 사용할 수 있습니다.

미리 감사드립니다.

답변

1

ViewChild을 사용하려고합니다. https://plnkr.co/edit/AkcKeInPxLRgNBPKiglk?p=preview

import {Component, NgModule, ViewChild, ElementRef} from '@angular/core' 
import {BrowserModule} from '@angular/platform-browser' 

@Component({ 
    //selector: 'my-app', // do NOT use in Ionic 
    template: ` 
    <div> 
     <h2 #headerWithRoute route="/any/route/here">Hello {{name}}</h2> 
    </div> 
    `, 
}) 
export class App { 

    @ViewChild('headerWithRoute') h2: ElementRef; 

    constructor() { 
    this.name = 'Angular2' 
    } 

    private _getAttributeValue(element: ElementRef, name: string, defaultVal: any): any { 
    let attribute = element.nativeElement.attributes.getNamedItem(name); 
    if (!attribute) return defaultVal; 
    return attribute.nodeValue; 
    } 

    ngAfterViewInit() { 
    // viewchilds are only valid after this event !! 

    console.log(this._getAttributeValue(this.h2, 'route')); 
    } 
} 

// do NOT use in Ionic 
//@NgModule({ 
// imports: [ BrowserModule ], 
// declarations: [ App ], 
// bootstrap: [ App ] 
//}) 
//export class AppModule {} 
+0

참고 :

이 데모 plunker을 참조하십시오 위대한 작품을 – Ivaro18

+0

를 도청 할이'NgModule'와'selector' 태그 @, 이러한 이온 성 내에서 작동하지 않고 응용 프로그램을 일으킬 수 있습니다 제거 , 정말 고맙습니다! 내가해야 할 일은 오류를 피하기 위해 기본 인수를 추가하는 것입니다 : this._getAttributeValue (this.h2, 'route', '/ default/route/here') – Scott

관련 문제