2017-10-19 42 views
0

我想获得服务输入的最大长度(通过http调用获取值)。Angular 2动态设置输入最大长度

有没有办法通过只调用一次服务来做到这一点?

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

感谢

回答

0

你可以得到最大的从服务的价值,并将其存储在本地值,可以直接绑定到的元素。

请找到实例中的链接

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; 

    } 
} 
0

在你component.ts

maxLenght:number = 0; 

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

然后在视图

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

0

构造过程中使用的方法调用和更新组件变量

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

1

设置maxlength属性值,其值在构造器或ngOnInit设置一个类属性将使其停止呼叫服务了

HTML:

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

打字稿

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

DEMO