Angular Attribute Binding via attr. results in null values when using #Attribute - html

If I use an angular component like this in my template:
<my-cmp selectable />
And my component asks the following in its constructor:
constructor(#Attribute("selectable") selectable: string){};
Then selectable will be an empty string, as expected, but when it is used like this:
<my-cmp [attr.selectable]="true" />
This will place the attribute correctly to my tag in the DOM and result in the following:
<my-cmp selectable="true" />
But in this case selectable will always have a null value, regardless if it is on construct or on ngOnInit and of its given value (e.g. false, "" or anything else will also result in null).
The question here is: why?
And more important: how to use boolean attributes in angular the best way?
Note: I explicitly don't want to use property-binding in this case, the given "input" should be static.

You can have some insight for the internals concerning #Attribute decorator here :
Angular does not read attribute values during runtime, only during
compile time, as otherwise we would get a performance hit.
With the <my-cmp [attr.selectable]="true" /> syntax, your are creating a binding. But the attribute value will be set after the first change detection cycle. So at compile time you will not have the attribute set, so you get a null value.

Related

concatenate variables in angular property element

I comment, and looked here and I can not find the solution, my problem is the following:
in my html template in angular, I need to pass a series of data to the metadata property of a button, I can't get the correct way to successfully concatenate the variable that contains the value.
this should be the html element:
<mati-button clientId="clientId" flowId="flowId" color="green"metadata='{"user_id":"1234778","email":"som#som.com"}'/>
I tried several ways but I can't insert the respective values....
example:
<mati-button metadata='{"userID": "{{user.id}}" }'></mati-button>
unsuccessfully...
Assuming mati-button is an Angular component with metadata as Input(), you are probably looking for
<mati-button
[clientId]="clientId"
[flowId]="flowId"
[color]="green"
[metadata]="{ userId: '1234778', email: 'som#som.com'}"
></mati-button>
See the guide on property binding to learn more:
To bind to an element's property, enclose it in square brackets, [], which identifies the property as a target property. [...] The brackets, [], cause Angular to evaluate the right-hand side of the assignment as a dynamic expression. Without the brackets, Angular treats the right-hand side as a string literal and sets the property to that static value.
By "dynamic expression" they mean JS-expressions, i.e., a public variable available through the component's TypeScript, a boolean expression, an array, or, like in your case, a JS-object that you can construct inline.
You can try doing this
<mati-button metadata="{'userID': user.id }"></mati-button>
metadata='{" userID ": {{user.id}}}'
in the end I got it. Apparently I don't know why, but the third-party script hides that parameter and it couldn't be debugged in the console, but it does receive them without any problem! Thanks everyone for your help!

Should you rather define several or only one input parameter (with all values) for child components

I am faced with the question of how I should set up my Angular components with regard to inputs.
The first variant would be to create an input variable for each given value. This means that you would have to enter each variable individually when calling it:
The second variant would be to pack all the required values ​​in a model and only include this model. So in the end only one input:
Now I don't know which of the two variants is better suited for a large app with many components.
Is there one i should prefer from these two or are there more i dont know yet?
It depends upon your component info what info you are passing for example if the component is a shared button in which expected inputs could be button name, class, status etc.
In that scenario instead of passing all inputs separately you could go with one object lets say props which contains button properties.
export interface IButtonProps {
text: string;
class: string;
disabled?: boolean;
}
buttonData: IButtonProps;
this.buttonData = {
...this.buttonData,
text: 'Submit',
class: 'primary',
disabled: false
}
In template instead of passing individual input pass an object of buttonData
<my-button [props]="buttonData"></my-button>
Your example doesn't really explain itself too well but here goes:
If your input's are all of the same type and used for the same thing, theres nothing wrong with putting all of them in an array and passing them to the child.
Instead of:
[input]="'string1'" [input2]="'string2'" you could do [input]="['string1', 'string2']"
However consider this:
[iconClass]="'my-icon-class'" [buttonClass]="'my-button-class'"
Each of the inputs do something completely different, so putting them inside of an array would be very bad practice.
What you could also do is put all inputs in an object, for example:
input = { iconClass: 'my-icon-class', buttonClass: 'my-button-class' };
[input]="input"
You should only be using this, if the inputs are somehow related or/and do the same thing / modify the same element in the child.

Angular - Two Way Binding

I am a beginner at Angular and I covering two way binding but for some reason I do not understand what I am doing wrong with the below any input would be appreciated.
I am simply trying to understand the concept so the below code is rather simple. Per my understanding
Adding the two way binding [()] to <app-child-comp> I pass the parent field "name" from the parent component to the parent view and using property binding it provides an initialization value ( default value ) to the child component that receives the value in the #Input field.
Once the field "#Input childName " has its value using normal interpolation I can use the value how ever I please in the child template.
Now by defining an EventEmitter and then using its .emit method I should be able to pass any changes on the variable back up to the parent component and update the DOM property to reflect the changes.
Problem:
Now this is my problem the parent --> child direction the bindings are working as intended,
the name "Fin" is appearing as I expect in the input of the parent Template and in the interpolation in the child template but when I want to alter the name in the child template and have it bubble back up to the parent property it fails to update although it updates the interpolation in the child template.
Ive been trying to figure this out now for a while and everything im researching I feel says im doing it correctly but if you could please explain what im doing wrong I would much appreciate it.
Im adding this so that anyone looking in the future can learn from my mistake.
There are two ways to perform event binding given a child component
The first way is by explicitly declaring the property and event bindings as follows <app-child-comp [childName]="name" (childNameChange)="name =$event"></app-child-comp>
The second way is to use the "Banana Box" Method where the child tag transforms into <app-child-comp [(childName)]="name"></app-child-comp>
I was trying to use the second method and something that wasn't immediately clear is that there is a naming convention when it comes to the field names in the child component that needs to be followed in order for the "Banana Method" to work
Rule: If your #Input field is named "x" then your #Output EventEmitter needs to be named "xChange" the "Change" is required as the second part of the name .
Syntax: inputName + Change
So in order to resolve my problem I needed to change the naming convention from
#Input() childName:string;
#Output() changedName = new EventEmitter<string>();
to
#Input() childName:string;
#Output() childNameChange = new EventEmitter<string>();
You have to add the output in your root component:
<app-child-app [(childName)]="name" (changedName)="name = $event"></app-child-app>

How does MVC decide which value to bind when there are multiple inputs with the same name?

I have an edit page where several fields are conditionally disabled, based on the user's role. When the fields are disabled, their values are not posted to the server (as expected), which causes the ModelState to be invalid, as the values are required.
To get around this, I want to add Html.HiddenFor() for the fields; so that a value will still get posted (and so that it will retain those values if the View is returned). However, in the case that those fields are not disabled, I will then have both a TextBoxFor and a HiddenFor going to the same model property.
I have run a couple tests, and it appears that when this happens, the value of the first element on the form will be binded to the model, while the next one just gets ignored. If this is the case, then I should be able to just put the HiddenFor after the TextBoxFor, in which case the value of the hidden input will only be posted when the regular input is disabled.
#Html.TextBoxFor(m => m.FirstName)
#Html.HiddenFor(m => m.FirstName) #*Only gets binded to the model if the above text box is disabled*#
(There is some JavaScript that conditionally disabled the visible TextBox).
So two questions: 1) Is it documented that MVC binding will always work this way; can I safely have both of these fields?
And, 2) Is there a better approach to accomplishing this? I know that I can but the HiddenFor inside an #If statement so that it will only get created if the TextBox is disabled; but that is a lot of extra logic in the View that I'd like to avoid.
The DefaultModelBinder reads the values from the request in order and binds the first matching name/value pair and ignores subsequent matches (unless the property is IEnumerable). This is how the CheckBoxFor() method ensures a true or false value is always submitted to the controller (the method generates a checkbox with value="True" and a hidden input with value="False"), so you can safely add the hidden input after the textbox.
One option you might consider rather than a disabled textbox, is to make it readonly, which means it will always submit a value, therefore you only need one input (and you can always style it to look disabled if that is what you want).

How can my text input be empty if the value attribute is set?

Have a look at the following screenshot. You can see that the text input field is empty, yet its value attribute is set to "b".
You'll also notice in the Properties tab, under input, that value here is set to "". Why are they different? What does this mean?
Could this be related to the fact that the input was rendered by React?
If it helps, here is the jsx responsible for this element (redacted):
return (
<td
key={field._id}
className={`oldField ${colPos}`}
>
<input
type="text"
defaultValue={value}
onChange={this.changeOldField(record, field)}
/>
</td>
)
It seems that you are changing the defaultValue based on something from the state. The defaultValue prop should be set only once and not changed later on, because any more changes will be ignored by React. If you want to change the value based on state you should use the normal value prop. Otherwise, if you want a predefined value to appear to the user and at the same time control the input when it gets changed, you can either use some logic in your code that handles both onChange and the code in your component that wants to automatically change the value, or possibly place it in the placeholder prop, which will give you something like what you want.