2017-08-07 66 views
0

我正在使用BackendLess構建Ionic項目。但我似乎無法使用打字稿文件中的HTML元素的ID。在離子2中使用getElementById

我在代碼中使用了@ViewChild。

HTML代碼:

<ion-item> 
    <ion-label floating>Name</ion-label> 
    <ion-input type="text" id="name"></ion-input> 
</ion-item> 

<ion-item> 
    <ion-label floating>Email</ion-label> 
    <ion-input type="email" id="email"></ion-input> 
</ion-item> 

<ion-item> 
    <ion-label floating>Password</ion-label> 
    <ion-input type="password" id="password"></ion-input> 
</ion-item> 

<ion-item> 
    <ion-label floating>Phone Number</ion-label> 
    <ion-input type="text" id="phone"></ion-input> 
</ion-item> 

<ion-item> 
    <ion-label floating>Profile Picture</ion-label> 
    <ion-input type="file" id="pic"></ion-input> 
</ion-item> 

<button ion-button (click)='userreg();'>Register</button></ion-content> 

打字稿代碼:

export class Register { 

    @ViewChild('name') name; 
    @ViewChild('email') email; 
    @ViewChild('password') password; 
    @ViewChild('phone') phone; 
    @ViewChild('pic') pic; 

constructor(public navCtrl: NavController, private alertCtrl: AlertController) { 
    } 

    ionViewDidLoad() { 
console.log('ionViewDidLoad Register'); 
    } 

    userreg() { 
    var picURL; 
    var user = new Backendless.User(); 
     user.email=this.email; 
     user.password=this.password; 
     user.name=this.name; 
     user.phone=this.phone; 

    Backendless.UserService.register(user).then(this.userRegistered).catch(this.gotError); 
} 

gotError(err) // see more on error handling 
    { 
    console.log("error message - " + err.message); 
     console.log("error code - " + err.statusCode); 
    } 

userRegistered(user) 
    { 
    console.log("User registered"); 
} 

} 

的@ViewChild似乎並沒有越來越值。我檢查了控制檯上的輸出,並顯示「Undefined」作爲輸出,因此不允許註冊到BackendLess中。

+2

請勿將鏈接發佈到外部來源。因爲它們可能會脫機,並且未來的用戶無法訪問它們。相反,只需將相關作品粘貼到問題中即可。 – Red

回答

0

@ViewChild("some-string")不會獲取標識爲some-string的元素,而是取代模板參考some-string。你可以給你的HTML元素的模板參考這樣的:

<ion-input type="email" #email></ion-input>

然後用它來獲取模板參考:

@ViewChild("email") email: ElementRef;

注意ElementRef就是你得到的類型。 ElementRef有一個名爲nativeElement的屬性,它是實際的HTMLElement(在這種情況下爲HTMLInputElement)。

重要提示:

既然你想要得到的HTML元素的值,而不是真正的引用,數據綁定將是更好的方法。下面是它如何工作的:

HTML:

<ion-item> 
    <ion-label floating>Name</ion-label> 
    <ion-input type="text" [(ngModel)]="name"></ion-input> 
</ion-item> 

然後你只需要在你的組件來定義屬性name

public name: string; 

角現在設定值自動爲您。

+0

因此,在這種情況下,我將如何使用ElementRef來獲取用戶提供的輸入值? –

+0

'email.nativeElement.ANY_HTML_PROPERTY'因此在這種情況下'email.nativeElement.value'。 – Wernerson

+0

但是,我不建議你閱讀這樣的值。有沒有聽說過數據綁定?檢查出來並嘗試使用它。 – Wernerson