0

I'm working on Angular application.

I have one & "Add" Button.

Now how can I implement functionality that can do: if there is not a single value in then if I hit Add button I should get an error. That error has to mentioned as "Please add something in textarea". If User has already added then Success.

Can please some help?

I have tried onSubmit() form but not working

1
  • Are you using reactive or template-driven forms? Commented Jan 23, 2023 at 23:05

2 Answers 2

1

In your typescript file, follow below steps

  1. Define FormGroup
addForm:FormGroup;
  1. Inject the FormBuilder Service in the constructor
constructor(private _formBuilder: FormBuilder){}
  1. Build Form in the ngOnInit Lifecycle
this.addForm = this._formBuilder.group({
    message: ['', [Validators.required]],
});

Now In your HTML file, use below code.

 <form [formGroup]="addForm">
    <mat-form-field [floatLabel]="'always'">
        <mat-label>Message</mat-label>
        <textarea matInput [rows]="3" [formControlName]="'message'"></textarea>
        <mat-error *ngIf="addForm.get('message').hasError('required')">
            Message is required.
        </mat-error>
    </mat-form-field>

    <button mat-flat-button [color]="'primary'" (click)="save()" [disabled]="addForm.invalid">
        <span>Save</span>
    </button>
</form>

If you want to disable until form validity then you can use invalid property of FormGroup as like I did.

Let me know if you've any queries. Happy Learning. ✌️

Sign up to request clarification or add additional context in comments.

2 Comments

What if I do not want to use Addform, Form Group Property
How to do "addForm:FormGroup;" in strict mode?
0
    If you don't want to use reactive forms:
    In your html:
    <textarea [(ngModel)]="textArea"></textarea>
    <button (click)="onSubmit()">Submit</button>
    In your ts:
      onSubmit() {
        console.log(this.textArea);
    if(this.textArea!=undefined){
        this.textArea = this.textArea.replace(/\s/g, '');
    }
        if (
          this.textArea == undefined ||
          this.textArea == '' ||
          this.textArea == null
        ) {
          alert('Please enter the data in text area!');
        } else {
          alert('data entered successfully');
        }
      }
    
    Use the following stackblitz link for reference: 

https://stackblitz.com/edit/angular-bx2xjc

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.