Choosing the initial choice with ngFor: A step-by-step guide

I'm having trouble selecting the first option after the user enters their email, but it remains unselected. Any ideas on how to solve this?

view image here

HTML Code:

<label for="login"><b>User:</b></label>
<input type="email" id="login" name="login" ngModel class="form-control" placeholder="Email"
required autofocus (focusout)="onSelect()">

 <label><b>Company:</b></label>
<select ngModel name="CompanyId" class="form-control" id="CompanyId" disabled="{{ disabled }}">
<option *ngFor="let company of companies; index as i" value="{{company.id}}"
>{{ company.name }}</option>
</select>

TypeScript Code:

onSelect() {
if ($("#login").val()== null || $("#login").val() =="") {

} else {
this.error = false;
this.alertService.clear();

let email = (document.getElementById("login") as HTMLInputElement).value;
localStorage.setItem(constants.emailSafeguard, email);

this.service.getCompanies(email).subscribe(list => {
this.companies = list;

if(list.length > 1) {
this.disabled = false;
} else {
this.disabled = true;
}
})
}

}

Answer №1

Your selection is currently empty. Please update it as follows:

<select [(ngModel)]="selectedEmpresaId" name="IdEmpresa" class="form-control" id="IdEmpresa" [disabled]="disabled">
<option *ngFor="let business of businesses; index as i" [value]="business.id">{{ business.name }}</option>
</select>

And in typescript (initial)

this.selectedEmpresaId = this.businesses[0].id;

Alternatively, you can use an object instead of an id

<select [(ngModel)]="selectedBusiness" name="IdBusiness" class="form-control" id="IdBusiness" [disabled]="disabled">
<option *ngFor="let business of businesses; index as i" [value]="business">{{ business.name }}</option>
</select>

And in typescript (initial)

this.selectedBusiness = this.businesses[0];

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

The specified type 'MutableRefObject<HTMLInputElement | undefined>' cannot be assigned to type 'LegacyRef<HTMLInputElement> | undefined'

Consider the following simplified component : const InputElement => React.forwardRef((props:any, ref) => { const handleRef = React.useRef<HTMLInputElement|undefined>() React.useImperativeHandle(ref, () => ({ setChecked(checke ...

Issue with Material UI v5: Uncaught TypeError - Unable to access properties of an undefined object (specifically 'create')

After setting up the ThemeSetting.tsx context, I encountered an issue where I could not utilize <Button><Button> and other components that rely on the theme from Material UI React.js in TypeScript: error TypeError: Cannot read properties of u ...

Disable inline imports when implementing an interface in vscode by selecting the "Implement interface" option

When using TypeScript, if I perform an auto-fix on a class name by selecting "Implement interface", it will generate the methods with inline imports like this: getInbox(): Observable<import('../../model/Message').Interactions[]> { t ...

How to toggle CSS class in Angular2/Typescript to mimic radio buttons behavior

Is there a way to create a radio button group using UL and LI elements in Angular2 and Typescript? The goal is to have all the anchors function like a radio button group where only one can be selected at a time. The selected anchor should remain "clicked" ...

Exploring Angular 10 Formly: How to Retrieve a Field's Value within a Personalized Formly Wrapper

Utilizing Angular 10, I have a formly-form with a select-field named session. This select field provides options from which to choose a dndSession. Each option holds key-value pairs within an object. I want to add a button next to the select-field that tr ...

Creating a universal timer at the application level in Angular

Is there a way to implement a timer that will automatically execute the logout() function in my authentication.service at a specific time, regardless of which page I am currently on within my application? I attempted to create a timer within my Authentica ...

When an empty array is returned from a catch statement in an async/await method, TypeScript infers it as never

Function getData() returns a Promise<Output[]>. When used without a catch statement, the inferred data type is Output[]. However, adding a catch statement in front of the getData() method changes the inferred data type to Output[] | void. This sugge ...

Utilize the text box feature for manipulating the data field in Angular4

Within my grid view, there exists a column labeled remark. This specific field contains various values, one of which is absence. My objective is to modify the remark value exclusively when it is equal to absence, followed by clicking the corresponding icon ...

The ngAfterViewChecked function seems to be caught in an endless loop

I am facing an issue where the <cdk-virtual-scroll-viewport> starts from the bottom, but I am unable to scroll up. I suspect that this problem is related to the use of AfterViewChecked. Even after trying AfterViewInit, the issue persists. @ViewChil ...

Using Typescript, invoke functions within an object by specifying a string key

I am looking for a way to call methods in an Object using string keys, but I'm facing issues with it. Could someone provide some solutions for this? type Methods = { foo?: (v: string) => string; bar?: (v: number) => number; baz?: (v ...

The numerical value of zero in React Native TypeScript is being interpreted as NaN

When attempting to map an array in React Native (Android) and use its values or keys as data for return, I encountered an issue where the value 0 is read as NaN. This problem also arose when utilizing a typescript enum. The versions I am using are: typesc ...

The property 'toLowerCase' cannot be accessed as it is undefined or null

Scenario: A textbox is present with a list of data below it. Upon typing in the textbox, the list gets filtered based on the text entered. Code: Pipe: @Pipe({ name: 'search' }) export class SearchPipe implements PipeTransform { transform( ...

What is the best way to implement an onChange handler for React-Select using TypeScript?

I am struggling to properly type the onchange function. I have created a handler function, but TypeScript keeps flagging a type mismatch issue. Here is my function: private handleChange(options: Array<{label: string, value: number}>) { } Typescrip ...

Error: Property 'content' is not defined and cannot be read

I encountered an issue with a config file while attempting to build with AOT using the command ionic cordova build android --prod Error: ./src/config/.env.ts Module build failed: TypeError: Cannot read property 'content' of undefined at Object ...

Adjust the color of an SVG icon depending on its 'liked' status

In my React/TypeScript app, I have implemented an Upvote component that allows users to upvote a post or remove their upvote. The icon used for the upvote is sourced from the Grommet-Icons section of the react-icons package. When a user clicks on the icon ...

Issue encountered with Angular 13 and Twilio Sync: The variable name is not recognized as a constructor, resulting in

After upgrading to angular 13, I encountered a problem that was not present when using angular 10. In my TwilioSyncService, the require statement is included in the constructor because it is an Injectable service requirement. The code snippet shows how t ...

Should the form-group class be utilized in Bootstrap 4 even without a form tag?

Is it considered good practice to use the form-group class without including a form tag? Dhiraj Dhakal ...

I am looking to have three rows of input text area comments instead of just one

Utilizing Bootstrap 4.3.1 with React Components I currently have this image: https://i.sstatic.net/rudsE.png And I am aiming for this design: https://i.sstatic.net/VmyTW.png comments: { elementLabel: "Comments", elementType: 'textar ...

Attempting to create distinct match matchups for every team in a manner reminiscent of the Swiss system format used in the 2024/25 UEFA Champion League

I've been working on devising a tournament pairing system modeled after the updated UEFA Champion League structure. The league phase involves 36 teams, categorized into 4 different pots. Each team is scheduled to play a total of 8 matches against 2 op ...

Defining TypeScript class events by extending EventEmitter

I have a class that extends EventEmitter and is capable of emitting the event hello. How can I properly declare the on method with a specific event name and listener signature? class MyClass extends events.EventEmitter { emitHello(name: string): void ...