1
votes

I'm using Angular CLI, Angular Material form and input. I developed a form to add a new hashtag inside.

I'm stuck at how to display every hashtag which were already added to the input.

Here is my code:

form.component.html

<form [formGroup]="createItemForm">
    <fieldset>
        <div class="row">
            <div class="col-lg-6">
                <mat-form-field>
                    <input formControlName="hashtag" matInput placeholder="Challenge hashtag"/>
                    <button matSuffix mat-button (click)="isShow = !isShow">Hashtag</button>
                </mat-form-field>
                <mat-form-field *ngIf="isShow">
                    <input matInput placeholder="Add a hashtag" [(ngModel)]="task" [ngModelOptions]="{standalone: true}"/>
                    <button matSuffix mat-button (click)="onClick()">Add</button>
                </mat-form-field>
            </div>
        </div>
    </fieldset>
    <button mat-raised-button type="submit" (click)="createItems()" class="btn btn-primary pull-right"
    [disabled]="!createItemForm.valid">Create a new items</button>
</form>

form.component.ts

task: string;
tasks = [];
isShow = false;

onClick() {
   this.tasks.push({name: this.task, strike: false});
   this.task = '';
}

and this is the output UI that I want to achieve enter image description here

2

2 Answers

1
votes

just set the value of the form control with the value you want it to display.

onClick() {
   this.tasks.push({name: this.task, strike: false});
   this.task = '';
   this.createItemForm.get('hashtag').setValue(this.tasks.map(t => '#' + t).join(', '))
}
1
votes

Push the new hashtags values by appending "#" to the form control

onClick() {
   this.tasks.push({'name': '#'+this.task, 'strike': false});
   this.task = '';
   this.createItemForm.controls.hashtag.setValue(this.tasks.reduce((a: string, t: any) => a.concat(t.name + ', '), ""));
}