Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

javascript - Need to use window.alert() method to get notify, that form field is empty, in Angular

What is the best way and how to display the text via window.alert() method in angular? To get known, when the form field wouldn't be filled, it should return the alert method, with the following message, as it's shown down:

Here, I have validation with a specific method.

This is my Component.ts code:

 task = {
    id: null,
    name : '',
    completed: false
  }
  taskForm = {
    name: new FormControl(this.task.name,[
      Validators.required
    ]),
  }
  tasks = TASKS;

  constructor(public taskService:TaskServiceService) {
  }
  ngOnInit(): void {
      this.getTasks();
  }
  addTask(task: NgForm){
    if(this.taskForm.name.invalid){
      alert('hey')
    } else {
    this.tasks.push(task.value);
    }
  }

Component.html with template driving form and couple of methods are here to:

    <button type="button" (click)="addTask(task); task.reset()" class="btn btn-outline-primary mb-2">Add</button>
 
question from:https://stackoverflow.com/questions/66062354/need-to-use-window-alert-method-to-get-notify-that-form-field-is-empty-in-an

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

On your ngOnChanges and ngOnInit , you can listen to your formControl changes and do something that you desire:

this.form.get('yourFormControlName')?.valueChanges.subscribe((value) => !!value ? window.alert('value is available') : window.alert('value is empty');

the two !! before value will coerce the value to a boolean so you can check whether or not it is empty


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...