1

I have a function in my ts file:

makeid(length) {
    var result = '';
    var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var charactersLength = characters.length;
    for ( var i = 0; i < length; i++ ) {
       result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
 }

And what I want is to return result of this function in my html. I can call a funtion in html like:

<input [readonly]="true" formControlName="caseId" matInput placeholder="Radni nalog br:" value="{{ makeid(15) }}">

But every time I click anywhere, it changes the value, and I'm getting an error:

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.

2 Answers 2

2

Every time the component reloads it will change because the function will run again. To keep the value of the first call use a variable to store the value on ngOnInit()

Examle:


x: string;


ngOnInit(){

    this.x = makeid(15)

}


makeid(length) {
    var result = '';
    var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var charactersLength = characters.length;
    for ( var i = 0; i < length; i++ ) {
       result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
 }

And in the HTML:


<input [readonly]="true" formControlName="caseId" matInput placeholder="Radni nalog br:" [value]="x">
Sign up to request clarification or add additional context in comments.

Comments

0

You should use [( ngModel )] or put a variable in your component.ts file and change that variable with your function and html will change automatically:

something like this

 <input id="Last Name" name="Last Name" type="text" [(ngModel)]="user.lastName" />

this stackblitz will help you https://stackblitz.com/edit/angular-6-value-changes-v2?file=src%2Fapp%2Fapp.component.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.