I have an AngularJS custom component that essentially wraps around a Material Design mdSelect, but provides easy configuration of available, default, and current values via its bindings.
But the component functions as a general editing component in an mdDialog that can change its options based upon the thing being edited. Thus is a "Next" button to go to the next "thing" to be edited. When the button is pressed the custom component will have new available, default, and current values—something like this:
<foo-component default-value="dialog.getDefaultFoo()" current-foo="dialog.currentFoo">
</foo-component>
Note that the component, if a list of available values is not given (as in the example above), the component assumes a list of values with only one value, the "default-value" indicated.
So when a user selects "Next", the list of values in the mdSelect will change, because the value returned by dialog.getDefaultFoo(). The new selected value will be dialog.currentFoo.
But if dialog.currentFoo is null, I want the control to automatically select the indicated default value, or if no default is indicated, the first available value. That's easy enough when the component is created using $onInit. But once it is created, how do I know (inside the component) that the user has selected "Next" and the list of available values has changed?
In the code for the "Next" button, I call this.fooForm.$setPristine(). According to the documentation, the when this method is called the form controller will "propagate to all the controls contained in this form." So I considered having my custom control hook detect that $setPristine() is being called, so that it can automatically select a default value from the list if the new value is null. But how now I'm back in the same situation: how does my custom component detect that $setPristine() is being called on the form?
In essence, my custom component needs to detect when one of its bound values changes, and perform some custom update of other values under certain conditions. I know that I can use a getter/settter from outside the custom component, but how does the custom component detect that one of its bound values has changed?
To make matters more complicated, dialog.currentFoo is actually a function, which my component recognizes as a getter/setter function which will return/update the correct value based upon the state of the dialog. So I can't even detect that this value has changed, because the actual function never changes—only the value that it returns will change.
And it's actually even more complicated than that, because the mdSelect is only one piece of the object that gets sent to dialog.currentFoo; otherwise it isn't propagated outside the component.
Trying to summarize, I need to know in a custom component if the binding dialog.currentFoo, which is really a getter/setter method, would now return null so that the custom component could select a default value (also dynamic) based upon the current items (also dynamic) listed in the internal mdSelect. I would accept workarounds, such as detecting that $setPristine() has been called on the enclosing form. I would even accept a hack, such as forcing AngularJS to recreate the custom component when some external state changes.
This is tricky, because AngularJS is tricky, and because it's exceedingly hard to track information on custom AngularJS control/input components.
Above all the first thing that needs to be done is to make the custom component use the normal ngModel framework; trying to "fake" it using a two-way bound currentValue doesn't cut it for this complexity, and besides, ngModel is the "correct" AngularJS way to do it. To pull this off you'll need to use NgModelController. Finding out how to do this with a component is difficult in itself, although one page gave the magic formula. It goes something like this:
require: {
ngModelCtrl: "ngModel"
},
bindings: {
ngModel: "<"
//TODO add defaultValue or whatever other properties here
},
Then you don't access the two-way value directly; you use the NgModelController interface:
//get the current value
const foo = this.ngModelCtrl.$modelValue;
//set the current value
this.ngModelCtrl.$setViewValue(foo);
As best I can tell, if you add ng-model-options="{getterSetter:true}" to the component, the ngModelOptions will automatically get applied to your model, and getters/setters will be called automatically.
Now you are hooked into the whole ngModel framework, and use NgModelController to add/access validators and all sorts of advanced features.
Getting back to my needs, where I need to "reset the component" in certain conditions, I can patch into NgModelController#$setPristine(). The form controller recognizes my component is part of the ngModel framework, and calls $setPristine() when the form is reset to its pristine state.
this.$onInit = () => {
this.ngModelCtrl.$setPristine = () => {
myInternalValue1 = null;
myInternalValue2 = this.defaultValue;
};
this.ngModelCtrl.$setPristine(); //initialize default value
};
This explains the doubt I had about the form controller "propagat[ing $setPristine()] to all the controls contained in this form", which I mentioned in my original question. The secret is that the component must become part of the real ngModel system so that it can interact as AngularJS is expecting, as well as to gain access to important internal methods.
Related
I am implementing a form in react using react hook form, The form has two select fields country and states.
Second field changes the option based on the selection in first field.
Please see the below sandbox for more details
Creating/submitting the record works perfectly fine.
The problem is: In edit, when I pre populate the values in the form using setValue(), it does not set the second dropdown(state select in the sandbox below) values on the UI but it shows that it has set the value to the field(see in the console for field state).
[CodeSandBox] https://codesandbox.io/s/angry-murdock-h0lbsp?file=/src/App.js
Steps to reproduce:
Open this sandbox in the browser.
Click on the SET ALL VALUES button.
See the blank value in states select
Also, Whats the best way to populate a form like this, i.e. in defaultsValues or useEffect?
What am I missing here, so putting it for the experts here.
Thanks for your time.
The problem you are having is about setValue. This function does not trigger a re-render in most cases. You can use reset instead.
https://react-hook-form.com/api/useform/reset
Also, if you'd like to fill the form without any user interaction, use reset in useEffect with proper dependencies.
Lastly, If you'd like to have just them having initial values instead of being undefined, set defaultValues. It is also recommended in official documents:
Important: You should provide a proper default value and avoid undefined.
undefined is reserved for fallback from inline
defaultValue/defaultChecked to hook level defaultValues. undefined value is conflicting with controlled component as default state
https://react-hook-form.com/api/useform
I have a Ant Design 4.x.x Form element without multiple Form.Item. I need to implement some logic involving form items' values, for example disabling a field if another one's value equals something, or recalculate select options when a text input changes.
To do so, I create the form using Form.useForm() and use form.getFieldValue() in my functional component body and / or in the returned JSX, like so :
It is working as I expect to, but at startup, getFieldValue usages throw annoying
index.js:1 Warning: Instance created by `useForm` is not connect to any Form element. Forget to pass `form` prop?
I found that Form functions cannot be used before rendering, and the problem also occured when displaying a form in a Modal like stated in the docs.
So I feel that I'm missing something on how to correctly add custom logic between fields, or doing some calculation involving fields values in component body.
What would be a correct approach to do this ?
Try adding getContainer={false}, to your modal this will work for you.
I was wondering is it a good practice to bind constant arguments to method in constructor or is there some better alternatives?
f.e.
constructor() {
super();
this.openModalWithFirstTabActive = this.openModal.bind(this, TAB.FIRST);
this.openModalWithSecondTabActive = this.openModal.bind(this, TAB.SECOND);
}
openModal(tabId) {
const {
openModal,
} = this.props;
/*
lots of logic and stuff
*/
openModal({
activeTabId: tabId,
...restProps,
});
}
EDIT
I'll provided more code and will describe my usage case for better understanding.
I've updated with openModal method, in my usecase it's much larger and has more logic in it.
So, i have a modal, in which there's two tabs. I have two buttons, open pressing button 1 modal needs to open and first tab needs to be active, upon pressing button 2 modal needs to open and second tab needs to be active.
I bind two methods in constructor which both call this.openModal only with different activeTabId specified. This avoids code duplication and arrow functions.
So my question would be is there any better alternative to this?
There is no point in binding a constant value to the function since they can directly be accessed inside the method. Also, since the binded arguments are the first to a function it might lead to confusion when debugging or handling the logic in the methods
When you use bind in constructor, it would lead to two instances of the function being created which is alright and won't affect the performance.
In case you have scenarios where you need to pass dynamic value to the methods without using bind in render, you can refer the following post
How to avoid bind or inline arrow functions inside render method
I'm new ot react native and am having a hard time with the idea of not using inheritance, but rather composition.
My scenario: I'm creating a component (focusedTextInput) which shows one InputText. My component simply adds functionality to change the style of the TextInput on focus.
I'm using FocusedTextInput in another component which contains five focusedTextInput and I configure those to only have one character at a time and to auto-skip to the next FocusedTextInput when the character is entered (using the focus() method).
Where I'm running into issues is the my FocusedTextInput does not have a focus method (and I don't want to expose the TextInput).
So do I need to surface all the method that might be used from TextInput on FocusedTextInput or is there a better way?
See this answer React set focus on input after render on stack overflow.
I think this applies to react-native but it does work in the web.
That shows you how to set a ref to a component. And in the CDM set the focus to that component.
To extend how that works so you can set the focus to a specific input (if there are many) is to add a prop called setFocused
Change the CDM to
// Set the focus on first render.
componentDidMount(){
if (this.props.setFocus) {
this.nameInput.focus();
}
}
// focus if the prop changes
componentWillRecieveProps(nextProps) {
if (this.nextProps.setFocus) {
this.nameInput.focus();
}
}
I'm running into a weird case that only seems to happen upon first loading a component on a heavily based component page (loading 30+ components).
#Component{
selector: <parent-component>
template: `<child-component [myObject]=myObject>
}
export class ParentComponent {
private myObject:DTOValue;
constructor(service:MyService){
service.getDTOValue().subscribe((dtoValue:DTOValue) => {
this.myObject = dtoValue;
});
}
}
#Component{
selector: <child-component>
template: `<div></div>
}
export class ChildComponent {
#Input set myObject(value:DTOValue) => {//do something};
constructor(){
}
}
In this code, the Parent is going to get a value to a child as an input. This value comes from a request at a later time, so when the child is first initialized, the input could be undefined. When the value does get returned from the request and is set on the variable myObject, I'd expect that the child component would receive an input event being triggered. However, due to the timing, it seems like this is not always the case, especially when I first load a page that contains a lot of files being loaded.
In the case that the child component doesn't receive the input, if I click else where on my page, it seems to now trigger the change detection and will get the input value.
The 2 possible solutions I can think of that would require some large code changes so I want to make sure I choose the right now before implement them.
Change the input to be an Subject, so that I push the input value which should ensure that a correct event is triggered(this seems like overkill).
Use the dynamic loader to load the component when the request as return with the correct value (also seems like overkill).
UPDATE:
Adding a plnker: http://plnkr.co/edit/1bUelmPFjwPDjUBDC4vb, you can see in here that the title seems to never get its data bindings applied.
Any suggestions would be appreciated.
Thanks!
If you can identify where the problem is and appropriate lifecycle hook where you could solve it, you can let Angular know using ChangeDetectorRef.
constructor(private _ref: ChangeDetectorRef)
method_where_changes_are_overlooked() {
do_something();
// tell angular to force change detection
this._ref.markForCheck();
}
I had a similar issue, only with router - it needed to do redirect when/if API server goes offline. I solved it by marking routerOnActivate() for check...
When you trigger change detection this way a "branch" of a component tree is marked for change detection, from this component to the app root. You can watch this talk by Victor Savkin about this subject...
Apologize, the issue ended up being my interaction with jQuery. When I triggered an event for a component to be loaded, inside of the jQuery code, it wouldn't trigger the life cycle. The fix was after the code was loaded to then call for a change detection.