The user must enter his username in the text field of the form. The accepted username is retrieved from the server and is 'Bret'. But everything the user enters in the field is accepted. How can I solve this problem?
app.component.html
<div id="details">
<form [formGroup]="form" (ngSubmit)="addDetails()">
<div class="form-group">
<label for="s_url">URL:</label>
<br>
<input style="width:80%" type="text" id="s_url" formControlName="s_url" />
<div style="color:red" *ngIf="s_url.value && s_url.invalid">
not a valid URL
</div>
</div>
<br>
<button type="submit" [disabled]="form.invalid">Submit</button>
<br>
<hr>
Form status:
<span [style.color]="form.status === 'VALID' ? 'green' : 'red'">
{{ form.status }}
</span>
<hr>
<pre>Form values: {{ form.value | json }}</pre>
<hr>
</form>
</div>
app.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { RouterModule } from '@angular/router';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.createForm();
}
createForm() {
fetch('https://jsonplaceholder.typicode.com/users')
.then((response) => response.json())
.then((json) => {
console.log(json[0].username);
this.reg = json[0].username;
});
const reg = this.reg;
this.form = this.fb.group({
s_url: ['', [Validators.required, Validators.pattern(reg)]],
});
}
// Getter for easy access
get s_url() {
return this.form.get('s_url');
}
// On submit
addDetails() {}
}
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
@NgModule({
imports: [ BrowserModule, FormsModule, ReactiveFormsModule ],
declarations: [ AppComponent, HelloComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Here is the live example: https://stackblitz.com/edit/angular-1kyxry