【问题标题】:Angular 2 set input max length dynamicallyAngular 2动态设置输入最大长度
【发布时间】:2018-03-31 10:40:54
【问题描述】:

我想从服务获取输入的最大长度(执行 http 调用以获取值)。

有没有办法只调用一次服务?

<input type="text" [attr.maxLength]="getMaxLength()/>

【问题讨论】:

    标签: javascript angular typescript rxjs observable


    【解决方案1】:

    您可以从服务中获取 max 的值并将其存储在本地值中,并且可以直接绑定到元素。

    请在链接中找到示例

    https://plnkr.co/edit/FX2DH96Femf02XwBUeCO

        @Component({
      selector: 'my-app',
      template: `
        <div>
          <h2>Hello {{name}}</h2>
          Quantity (between 10 and 100):
          <input type="number" name="quantity" min="{{min}}" max="{{max}}">
          <br/>
          Name (max length - 10 character)
          <input type="text" name="name" [attr.maxLength]="maxTextLen">
        </div>
      `,
    })
    export class App {
      name:string;
      min : number;
      max : number;
      maxTextLen;
    
      constructor() {
        this.name = `Angular! v${VERSION.full}`
        this.min = 10;
        this.max = 100;
        this.maxTextLen = 10;
    
      }
    }
    

    【讨论】:

      【解决方案2】:

      在你的component.ts

      maxLenght:number = 0;
      
      ngOnInit() {
        this.service.getMaxLength()
          .subscribe(max => {
            this.maxLenght = max;
           });
      }
      

      然后在视图中

      &lt;input type="text" [attr.maxLength]="maxLength"/&gt;

      【讨论】:

        【解决方案3】:

        在构造函数期间使用方法调用并更新组件变量

        constructor(private _http: Http) {
            this.getMaxLength().subscribe(data=>{
              console.log(data)
              this.maxLength= data;
              })
        
          }
          getMaxLength(): Observable<number> {
                return this._http.get(this._url)
                    .map((response: Response) => response.json())
                    .catch(this.handleError);
            }
        

        LIVE DEMO

        【讨论】:

          【解决方案4】:

          将 maxLength 属性值设置为在 contructor 或 ngOnInit 中设置的类属性将使其不再调用服务

          HTML:

          <input type="text" [maxLength]="maxLength"/>
          

          打字稿

            maxLength: number;
            .....
            constructor(private myService: MyService){
              this.maxLength =  this.myService.getMaxLength();
            }
          

          DEMO

          【讨论】:

          • 这有帮助吗?如果是,你介意接受吗?
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-06-02
          • 1970-01-01
          • 2022-01-17
          • 2017-10-19
          • 1970-01-01
          • 2011-02-01
          • 2012-09-27
          相关资源
          最近更新 更多