2017-08-07 64 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