2017-10-19 24 views
0

Je voudrais obtenir la longueur maximale d'une entrée d'un service (faire un appel http pour obtenir la valeur).Angular 2 règle la longueur maximale de l'entrée

Y a-t-il un moyen de le faire en appelant le service une seule fois?

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

grâce

Répondre

0

Vous pouvez obtenir la valeur de maximum du service et le stocker dans une valeur locale et qui peut être lié directement à l'élément.

S'il vous plaît trouver l'exemple dans le lien

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

Dans votre component.ts

maxLenght:number = 0; 

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

puis dans la vue

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

0

Utilisez l'appel de méthode au cours du constructeur et mettre à jour une variable composante

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

Réglage maxLength valeur de l'attribut à une propriété de classe dont la valeur est définie dans contructor ou ngOnInit va faire cesser d'appeler le service plus

HTML:

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

Tapuscrit

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

DEMO