htmlionic3textareaangular6angular4-forms

Angular 4 - On button click want to append textarea to view dynamically for each button click


Actually I want to create one textarea on button click over view. I don't have much idea in angular 4. Requirement is that on each click of button I want to create textarea over view. There should be multiple textarea's with cross buttons so I can remove the textarea if don't want.

Unfortunately I didn't try any code yet and didn't found any solution to implement it. But that is my requirement to create in angular 4. Any help will be appreciable.


Solution

  • Below code will serve your requirement of generating textarea on button click as well as removing specific textarea.

    <div style="padding-top: 200px">
    <button (click)="addTextarea()">Add Textarea</button>
    <form>
        <div *ngFor="let textarea of textAreasList; let textarea_index= index">
            <textarea name="{{textarea}}"></textarea>
            <button (click)="removeTextArea(textarea_index)">Remove</button>
        </div>
    </form>
    

    place the above code in .html file.

    import { Component } from '@angular/core';
    
    @Component({
        selector: 'home',
        templateUrl: 'home.component.html',
        styleUrls: ['home.component.css']
    })
    export class HomeComponent {
    
        textAreasList:any = [];
    
        addTextarea(){        
            this.textAreasList.push('text_area'+ (this.textAreasList.length + 1));
        }
    
    
        removeTextArea(index){
            this.textAreasList.splice(index, 1);
        }
    
    }
    

    place the above code in .ts file. Let me know if you have any other difficulties.