Angular Form: displaying multiple hashtags within an input field

Utilizing Angular CLI and Angular Material, I have created a form to input new hashtags.

I am facing difficulty in displaying previously added hashtags in the input field.

Below is the code I have written:

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 here's the visual UI output that I am striving for: https://i.stack.imgur.com/Fy2vv.png

Answer №1

To update the form control's value, simply assign the desired value to it.

onSubmit() {
   this.items.push({title: this.item, completed: false});
   this.item = '';
   this.formGroup.get('tags').setValue(this.items.map(i => '#' + i.title).join(', '))
}

Answer №2

Add new hashtags to the list by including "#" in the input field

handleClick() {
   this.items.push({'name': '#'+this.item, 'completed': false});
   this.item = '';
   this.tagForm.controls.hashtags.setValue(this.items.reduce((prev: string, cur: any) => prev.concat(cur.name + ', '), ""));
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble accessing the theme in a styled component with @emotion/styled

https://i.stack.imgur.com/zHLON.png I've been using @emotion/react for theming and successfully injected the theme into it. I can access the theme using useTheme within components, but I'm facing some difficulties in accessing the theme within s ...

Using Typescript to define custom PopperComponent props in Material UI

I'm currently utilizing the Material UI autocomplete feature in my React and Typescript application. I'm looking to create a custom popper component to ensure that the popper is full-width. Here's how I can achieve this: const CustomPopper ...

Working with JSON data in AngularJS2's templates

Is there a way for me to process JSON from the template in a manner similar to the second code I provided? First code. This method works well when using .json and .map () @Component({ ..// template: `..// <li *ngFor="#user of users"> ...

Struggling to determine data type in Typescript

My goal is to create an interface for my realm Database using TypeScript. Essentially, I have an automation bot and I want to monitor and track how users are utilizing it. To achieve this, I have designed specific schemas that will be integrated into an i ...

The error message "TypeError: self.parent.parent.context.parseInt is not a function" indicates that

My goal is to set the height of an image using ngStyle by calculating it with a Math operation in the following way: <div [ngSwitch]="tbNm?tbNm:'itm0'"> <ion-list *ngFor="let vl of scrnshot;let ind=index"> <img *ngSwitch ...

Setting the height of CKEditor 5: A comprehensive guide

How can I adjust the height of the CKeditor angular component? The documentation suggests we can set the editor style to: min-height: 500px !important; However, this solution does not seem to be effective for me. Any other suggestions? ...

Utilize global variables in ng-apimock mocks without the need for double quotes

We integrated ng-apimock into our Angular project and successfully created mock definitions and wrote tests using protractor. Now we are looking to implement global variables in our mock definitions. Here is an example of a mock definition: { "expressi ...

Troubleshooting the error message "TypeError: Cannot read property 'name' of undefined" when working with data binding in Angular 4

I am brand new to Angular and I have been working on creating a custom Component. Specifically, I am trying to display a list of Courses (objects) which consist of two properties: id and name. So far, this logic is functioning properly. However, when attem ...

Encountering a Typescript Type error when attempting to include a new custom property 'tab' within the 'Typography' component in a Material UI theme

Currently, I am encountering a Typescript Type error when attempting to add a custom new property called 'tab' inside 'Typography' in my Material UI Theme. The error message states: Property 'tab' does not exist on type &apos ...

After installing Highcharts, an error occurs stating 'Highcarts is not defined'

I am trying to incorporate Highcharts into an Angular 5 project using the ng2-highcharts npm package. However, I keep encountering an error stating that 'highcharts is not defined'. In my Angular 5 project, I have integrated Highcharts and utili ...

The submit button seems to be unresponsive or unreactive

As a newcomer to Angular 2 and Typescript, I am in the process of building a web application. I have created several input fields and, following user submission via a button, I want to log the inputs to the console. However, it seems like my button is not ...

Ways to employ a Hyphen(-) to connect two strings within an ngIf condition in Angular 9

I'm dealing with an IF condition in HTML that checks for permission to access a specific page: *ngIf="permission?.product-report?.list_product_report" The name "product-report" is static and directly used in the condition. However, whe ...

Is it possible to devise a universal click handler in TypeScript that will consistently execute after all other click handlers?

In my ReactJS based application written in TypeScript, we have implemented various click handlers. Different teams contribute to the application and can add their own handlers as well. The challenge we face is ensuring that a specific global click handler ...

Error in NextJS with TypeScript when updating data in a useState variable

Recently, I started working with TypeScript, ReactJS, and NextJS, but I encountered a TypeScript error that I need help fixing. My current project involves using NextJS 14, server actions, and Prisma as the ORM for a university-related project. An issue ar ...

Encountering difficulties in setting up ng zorro using Angular CLI for installation

I'm facing an issue with installing ng-zorro. Every time I try to run the command ng add ng-zorro-antd, I encounter an error: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/c ...

The CSS transition timing seems to be malfunctioning as not all elements are smoothly transitioning, specifically the text within the li and anchor tags is not

I'm attempting to achieve a smooth transition effect on a navbar when hovering over it, changing the color from one to another. The navbar contains a list of words, but I am encountering an issue where during the transition, there is a quick flash (ap ...

"Utilize an Angular button to upload a locally stored JSON file and populate a data

Hey everyone, I'm looking to use a button to load a local file and convert the file data into a jsonObject. The HTML structure: <div class="uuidLableLeft"> <b>Do you want to import your previous file (.json)?</b> <input style ...

What is the process for extracting components from a JSON file using an observable in Angular?

Take a look at this snippet of code: response: any; fetchData(url: any) { this.response = this.http.get(url); } ngOnInit(): void { fetchData("url.com/data.json"); console.log(this.response) } When I check the console, I see Obser ...

Tips for using a loop variable as an argument in a method call for an attribute reference

Within the html code of my component, I have the following: <div *ngFor="let image of images; let i=index;" class="m-image-wrapper"> <i class="fa fa-times m-delete-img" (click)="removeImage(i, {{image.docname ...

Changing the Month Label Format from Short (MMM) to Long (MMMM) in Angular Material Datepicker

I am looking to customize the month labels in Angular Material datepicker. By default, the month view displays in MMM format and I want to change it to MMMM using custom MatDateFormats. export const APP_DATE_FORMATS: MatDateFormats = { parse: { dat ...