2

I have two radio buttons (they're not dynamically generated):

<input type="radio" name="orderbydescending" [(ngModel)]="orderbydescending" [value]="['+recordStartDate']">Ascending<br>
<input type="radio" name="orderbydescending" [(ngModel)]="orderbydescending" [value]="['-recordStartDate']">Descending

How do I make one of the radio buttons checked by default?

Thank you!

Edit

The button's values are being passed through this pipe (i.e. not a component, per se...not sure this is worth mentioning?). The app is pretty simple, and the radio buttons are just hardcoded into app.component. Is the pipe the correct place to initialize which radio button is checked by default?

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'orderBy', pure: false})
export class OrderByPipe implements PipeTransform {

static _OrderByPipeComparator(a:any, b:any):number{

  if((isNaN(parseFloat(a)) || !isFinite(a)) || (isNaN(parseFloat(b)) || !isFinite(b))){
    //Isn't a number so lowercase the string to properly compare
    if(a.toLowerCase() < b.toLowerCase()) return -1;
    if(a.toLowerCase() > b.toLowerCase()) return 1;
  }
  else{
    //Parse strings as numbers to compare properly
    if(parseFloat(a) < parseFloat(b)) return -1;
    if(parseFloat(a) > parseFloat(b)) return 1;
  }

  return 0; //equal each other
}

transform(input:any, [config = '+']): any{

    if(!Array.isArray(input)) return input;

    if(!Array.isArray(config) || (Array.isArray(config) && config.length == 1)){
        var propertyToCheck:string = !Array.isArray(config) ? config : config[0];
        var desc = propertyToCheck.substr(0, 1) == '-';

        //Basic array
        if(!propertyToCheck || propertyToCheck == '-' || propertyToCheck == '+'){
            return !desc ? input.sort() : input.sort().reverse();
        }
        else {
            var property:string = propertyToCheck.substr(0, 1) == '+' || propertyToCheck.substr(0, 1) == '-'
                ? propertyToCheck.substr(1)
                : propertyToCheck;

            return input.sort(function(a:any,b:any){
                return !desc
                    ? OrderByPipe._OrderByPipeComparator(a[property], b[property])
                    : -OrderByPipe._OrderByPipeComparator(a[property], b[property]);
            });
        }
    }
    else {
        //Loop over property of the array in order and sort
        return input.sort(function(a:any,b:any){
            for(var i:number = 0; i < config.length; i++){
                var desc = config[i].substr(0, 1) == '-';
                var property = config[i].substr(0, 1) == '+' || config[i].substr(0, 1) == '-'
                    ? config[i].substr(1)
                    : config[i];

                var comparison = !desc
                    ? OrderByPipe._OrderByPipeComparator(a[property], b[property])
                    : -OrderByPipe._OrderByPipeComparator(a[property], b[property]);

                //Don't return 0 yet in case of needing to sort by next property
                if(comparison != 0) return comparison;
            }

            return 0; //equal each other
        });
    }
 }

Edit 2

So in component.app.ts I've edited my export class AppComponent{ to the following:

export class AppComponent {
  artists = ARTISTS;
  currentArtist: Artist;
  orderbydescending = ['-recordStartDate'];

showArtist(item) {
  this.currentArtist = item;

} }

This works in terms of preventing the previous errors, but it doesn't actually make the radio button selected. It still appears as though it's unselected - even though it functions as though it is. Does this make sense?

3 Answers 3

1

If you're doing this in Angular 2+ with 2 way binding, in the component where this HTML is being used, you could just try initializing the value associated with the input.

// in your component ts file
orderbydescending: boolean = true;

and you could leave the HTML the same. Although, you seem to have 2 radio buttons associated with the same data value, orderbydescending. I don't know if that's what you intend, but it looks like it could cause problems.

Here's some code from my personal side project to give you a better idea.

@Component({
  selector: 'gmu-home-page',
  templateUrl: './home-page.component.html',
  styleUrls: ['./home-page.component.css']
})
export class HomePageComponent implements OnInit {
  // here you would put your variables
  myFlag: boolean = true;
  constructor() { }
  ngOnInit() {
  }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Is this what you mean? @Component({ selector: 'app', templateUrl: '../partials/app.html', styleUrls: [ '../css/app.css' ], orderbydescending: boolean = true; }) if so, I get the following error when compiling: orderbydescending: boolean; }' is not assignable to parameter of type 'Component'. Object literal may only specify known properties, and 'orderbydescending' does not exist in type 'Component'. Perhaps I'm misunderstanding. (Also, the radio button values are indeed correct, the values are different, "+" v "-".
Take a look at what I added to my answer. It's a syntactical thing. You probably need to look at more examples of Angular code. This is a great guide written by the Angular folks, and is how I got started. angular.io/tutorial
Yup -- you're correct! I'm brand new to Angular, and I rushed past some fundamentals. Thanks for your help/patience. In the mean time, I've updated my question to include the pipe to which the radio values are being passed. Including orderbydescending = ['+recordStartDate']; within the pipe doesn't seem to do the trick either.
Is there any particular reason you are passing the value through a pipe? If you're using a radio button, I'm assuming you're using it to select between some predetermined values. orderbydescending indicates to me that you are trying to switch between different modes of sorting. I'm not entirely sure where recordStartDate falls into this. Could you elaborate on what that's for? What's the use case for not defining your radio button state within the component it is used for?
I'm sorting objects within an array in a local .json file, and my recordStartDate key-value pair is the parameter by which I'm trying to sort. I'm trying to replicate the functionality seen here: fuelinteractive.github.io/fuel-ui/#/pipe/orderby. -- In any case, I've actually got it working, see Edit 2, the only issue is that even though it works, the button still appears unchecked. Seems odd...
|
1

If orderbydescending and recordStartDate are members of your component class:

@Component({
    ...
})
export class MyComponent {
    public recordStartDate: any = ... 
    public orderbydescending: any = +recordStartDate;
    ...
}

the appropriate radio button will be checked if you assign the radio button values with [value]:

<input type="radio" name="order" [(ngModel)]="orderbydescending" [value]="+recordStartDate">Ascending<br>
<input type="radio" name="order" [(ngModel)]="orderbydescending" [value]="-recordStartDate">Descending

In the case shown above, the ascending order radio button will be checked by default because the orderbydescending variable is initially set to +recordStartDate.

Note: The variables in my sample code are of type any because I don't know exactly what kind of data you are using. Your data will probably have a more specific data type.

4 Comments

Thanks, ConnorsFan! This functions correctly, but oddly, the button still appears unchecked. Does this make sense/do you know how to fix it?
In my own code, I use that technique with integers and booleans, and it works. If the variable associated with ngModel is initialized, the corresponding radio button is checked by default (e.g. [(ngModel)]="orderbydescending" [value]="5", with public orderbydescending: number = 5;. For debugging, you can try that first (with hard coded values).
By the way, in your edited post, you now assign an array as the value of the radio button, and you set the value of orderbydescending also to an array in code. But these arrays are not the same object, so they are not equal. You should use a single value for the value of the radio button and for orderbydescending, not an array. Use an integer, or a boolean, or a string, something like that.
Yes -- I'm realizing now that this is the problem, thank you! However, for my pipe to work, I need the values to be within [' and ']. I'm trying to replicate the functionality seen here, using the same pipe: http://fuelinteractive.github.io/fuel-ui/#/pipe/orderby. I'm sorting objects within an array in a local .json file, and my recordStartDate is the key/value pair by which I'm trying to sort.
1

Try this in the component

radioValue = {valueAsc: 'Asc', valueDesc: 'Desc'} ;
orderbydescending = 'Asc';

and in the template put this

<input type="radio" name="radioGroup" [(ngModel)]="orderbydescending" [value]="radioValue.valueAsc">Ascending

<input type="radio" name="radioGroup" [(ngModel)]="orderbydescending" [value]="radioValue.valueDesc">Descending

With this the first radio button is checked, if you don't want any radio button selected assign to the variable orderbydescending null.

orderbydescending = 'null;

3 Comments

Doesn't seem to work. The associated button remains unchecked. Everything compiles fine and there're no console errors.
You can put a plunker, there works. Who is orderbydescending and what value has it
Interesting... it does work in plunker. The problem must be elsewhere.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.