display angular filter for mat radio option selected from mat-radio group

On the screenshot provided below, there are 2 buttons within a mat radio group. The condition is that if modelForm.get('schedule').value equals '1', then only display the radio button with the value 'A'. Otherwise, show all values from stages which include 'A' and 'B'.

How can we achieve this? Is it possible to selectively hide buttons within a loop based on a specific value? Thank you.

#SCREENSHOT https://i.sstatic.net/1RmYP.png

#html

<mat-radio-group [disabled]="!modelForm.get('schedule').value" [(ngModel)]="stage" layout="column">
                        <mat-radio-button *ngFor="let stage of stages" [value]="stage.text" color="primary">
                          {{ stage.text }}
                        </mat-radio-button>
                      </mat-radio-group>

#TS

  stages = [
    {id: 0, text: 'A'},
    {id: 1, text: 'B'},
  ]

Answer №1

Try using the following instead of `[hidden]`:

[style.display]="isHidden(stage)?'none':null"

Another approach could be:

<mat-radio-group [(ngModel)]="stage" layout="column">
  <!--always show the first item, use "stages[0]"-->
  <mat-radio-button [value]="stages[0].text">
    {{ stages[0].text }}
  </mat-radio-button>

  <!--show the rest based on condition-->
  <ng-container *ngIf="modelForm.get('schedule').value !== '1'">
    <ng-container *ngFor="let stage of stages; let first=first">
      <mat-radio-button *ngIf="!first" [value]="stage.text" color="primary">
        {{ stage.text }}
      </mat-radio-button>
    </ng-container>
  </ng-container>
</mat-radio-group>

Answer №2

Important: It is crucial to remember that when the schedule value is switched to 1, you must programmatically set the stage property to 'A' for this solution to function correctly!

Utilizing html classes can help with hiding and displaying elements.

Check out the stackblitz demo here

<mat-radio-group
      [disabled]="!formGroup.get('password').value"
      [(ngModel)]="stage"
      [ngModelOptions]="{ standalone: true }"
      layout="column"
    >
      <mat-radio-button
        *ngFor="let stage of stages"
        [value]="stage.text"
        color="primary"
        [ngClass]="{ isHidden: isHidden(stage) }"
      >
        {{ stage.text }}
      </mat-radio-button>
    </mat-radio-group>

styles.css

.isHidden {
  visibility: hidden;
  width: 0;
}

ts

import { Component } from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  FormControl,
  Validators,
} from '@angular/forms';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  formGroup: FormGroup;
  titleAlert: string = 'This field is required';
  post: any = '';
  stages = [
    { id: 0, text: 'A' },
    { id: 1, text: 'B' },
  ];

  isHidden(stage) {
    return (
      this.formGroup.get('password').value === '1' && stage && stage.id === 1
    );
  }

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

Ways to restrict users from inputting alphabets in TextField using material ui

I've set up a TextField where users can only input positive digits. Currently, I'm using the following onKeyDown event: <TextField label={distanceError} error={!!distanceError} defaultValue={kpoints.distance} on ...

A Typescript type that verifies whether a provided key, when used in an object, resolves to an array

I have a theoretical question regarding creating an input type that checks if a specific enum key, when passed as a key to an object, resolves to an array. Allow me to illustrate this with an example: enum FormKeys { x = "x", y = "y&q ...

Iterating through each loop and storing the values in an array

After researching various topics related to the issue, I found that the solutions provided are not working for me. It seems like there is a logic problem in my code. It's quite simple - I have two arrays (one containing three strings and the other con ...

WebStorm failing to identify Node.js functions

I recently began my journey in learning node.js and I'm currently utilizing WebStorm 11 as my preferred IDE. However, I've encountered an issue where WebStorm does not seem to recognize the writeHead method: var http = require("http"); http.cre ...

Is there an optimal method for executing shell commands quickly in Node.js?

How can I efficiently run a large number of shell commands sequentially, for example 50 or 60 commands one after the other? For instance: const arr = ['/hello', '/temp', '/temp2', '/temp3', '/temp5', ...... ...

How can I invoke TypeScript methods within a jQuery event handler in the ngAfterViewInit lifecycle hook?

I am currently utilizing Angular 4. I need to invoke methods from a typescript file within the ngAfterViewInit method. declare var $; @Component({ selector: 'app-details', templateUrl: './details.component.html', styleUrls: [&apo ...

Using Regular Expression to verify the presence of numbers and spaces

Currently, I have implemented a regular expression that ensures my string contains 5 digits. While this regex works flawlessly, I now also require it to allow white spaces: both "123 45" and "12345" should meet the criteria. string.match(/^\d{5}$/g); ...

Handling Movement Events in PrimeNG PickList ComponentsExplore the onMove and onMoveAll event

I am currently utilizing PrimeNG PickList version 5.0.0-rc0 in my Angular 5 project. An issue I am encountering is that the functions onMoveToTarget and onMoveAllToTarget are being triggered simultaneously, which, in my opinion, should not happen. The Pick ...

What is the best approach for replacing numerous maps within an rxjs observable array?

Is there a more efficient way to retrieve only 3 items from an array? If you have any suggestions, I would appreciate it! Thank you. loadAsk!: Observable<any[]>; this.loadAsk.pipe( map(arr => arr.sort(() => Math.random() - .5)), map((item ...

Exciting discovery within my coding for US Number formatting!

I am currently working on formatting 10 digits to resemble a US telephone number format, such as (###) ###-####. Although my code successfully achieves this goal, it also has an unexpected issue that I'm struggling to identify. Specifically, when ente ...

What could be causing the JavaScript/jquery code in my Functions.php file to only function properly on the initial post that loads on my WordPress website?

Currently, I am in the process of developing a WordPress website where the content is refreshed weekly. This means that all posts, media, and files are removed from the WP environment every week and replaced with new content. One of the key components of ...

Displaying a disabled div depending on the dropdown selection in Angular Material

My goal is to display filters in a dropdown after they have been selected. Currently, I have static disabled divs and a dropdown where filters can be selected. This is the dropdown: <mat-form-field> <mat-label>{{ 'supplier.showFilters&a ...

The functionality of event bubbling appears to be ineffective while utilizing a bootstrap modal in an AngularJS application

I have a question regarding the use of Bootstrap modal. To begin with, I apologize for any issues in understanding my question due to my English skills. I have created a button as a directive to dynamically add, with reference to the following links. . ...

Learn how to dynamically add and remove a CSS class from an element using a scroll event in Angular 7

My goal is to create a navbar that gains a "fixed-top" class during scrolling and removes it when it reaches the top of the page. I've written the following script, but unfortunately, it's not working as expected. import { Component, OnInit, Af ...

Having difficulty executing a loop on the JSON response object

I've stored categories and their types in a dictionary in a .cs file, like this: Dictionary<string, List<string>> jsonDic To convert it into a JSON object string, I used the following logic: JavaScriptSerializer jss = new JavaScriptSe ...

Tips for coordinating external asynchronous JavaScript retrieval

Within my app.js file, I have the following code snippet: load(src) { var script = document.createElement('script'); script.src = src; script.async = true; document.head.appendChild(script); } for (var i=0; scripts.length; i++) { loa ...

Placing emphasis on an object that appears following a period of waiting

I'm currently working on enhancing the accessibility of a slider that will be featured on my website. The goal is to create an effect where, after clicking (or pressing enter) on the first slide, the focus shifts to the second slide element, allowing ...

The Issue with NG-Zorro Datepicker Manual Input Mask Functionality未分类

Is there a way to mask the datepicker so that users can enter dates in the format MM/dd/yyyy without typing the "/" character manually? I've tried using ngx-mask but it doesn't seem to work for the datepicker component. I have provided a link to ...

What is the best way to display a jQuery UI dialog when the page is reloaded?

I am trying to display a jQuery UI dialog when the user tries to reload or close the browser. Here is my code snippet: $(window).bind('beforeunload', function () { $("#confirm").dialog({ width: 500, modal: true, buttons: { ...

How can one correctly log out of an Angular application that is integrated with Firebase Authentication and Firestore?

How can I efficiently sign out of an Angular application that uses Firebase Authentication and Firestore? Although I can successfully sign in with Google authentication, signing out poses some challenges. My ultimate goal is to ensure that when a user cli ...