【问题标题】:Get the value from the mat-input in angular material从角度材料中的垫子输入中获取值
【发布时间】:2021-03-14 04:33:29
【问题描述】:

对于角度来说,我是新手。我只想从 mat-input 中获取值 我需要从角度垫输入中获取值。 有人可以帮我做到这一点。 提前致谢

<div fxLayoutAlign= "center center" fxFlexFill class="main-div">
<mat-card fxFlex= "20">
    <mat-toolbar color="primary" c>Bonbloc Login</mat-toolbar>
    <form fxLayoutAlign="stretch" fxLayout = "column" class="login-form">
        <mat-form-field>
          <input matInput required [(ngModel)] = "email" placeholder="email Id">
          <mat-hint align="end">Min 5 characters</mat-hint>
        </mat-form-field>

        <mat-form-field>
          <input matInput required [(ngModel)] = "password" type="password" placeholder="password">
        </mat-form-field>
        <button mat-raised-button type="submit" (click) = "login()">Login</button>
        <h1>Hi {{email}} {{password}}</h1>
      </form>
</mat-card>
login() {
console.log(this.email, this.password)
};

【问题讨论】:

标签: angular angular-material mat-input


【解决方案1】:

它的哪一部分不能正常工作?看起来应该没问题。

<input matInput required [(ngModel)]="email" placeholder="email Id">

大概你在.ts 中有一个匹配的行声明了一个email 字段来绑定:

public email: string;

或类似的。

[(ngModel)] 是双向绑定,这意味着您以编程方式设置email 的任何内容都将放入文本框中,而用户放入文本框中的任何内容都将设置email 的值。

您的login() 方法应该能够看到这个...

public login(): void {
  console.log('Entered email:', this.email);
}

编辑:示例StackBlitz 显示基本绑定工作。不使用matInput,但这不会改变功能。

【讨论】:

  • 如果我需要从输入字段本身获取输入。我不需要在文本框中输入值意味着我应该怎么做..???
  • 我已经粘贴了上面的登录代码。但它不起作用
  • 我添加了一个 StackBlitz,显示您尝试使用的基本机制。
【解决方案2】:

html

<input matInput required [(ngModel)]="email" [value]="email" placeholder="your email" (change)="valuechange($event)">

component.ts

private email : string = '';

  valuechange() {
    console.log(this.email);
  }

ng-model 指令将输入、选择、文本区域等 HTML 控件的值绑定到在 ts 文件中创建的变量。所以它可以作为双向绑定

【讨论】:

    【解决方案3】:

    也可以使用这个名字

    <mat-form-field appearance="fill">
        <form>
           <mat-label>Insert Anything</mat-label>
           <input type="text"  matInput [(ngModel)] ="oName" name="oName" >
           <mat-hint>Serie</mat-hint>
        </form>
    </mat-form-field>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      • 2019-03-10
      • 1970-01-01
      • 2019-05-07
      • 2017-01-03
      • 2018-11-07
      相关资源
      最近更新 更多