that's my html code
<optimus-mat-form-field type="input" class="optimus-mat-form-field-width-50">
<mat-form-field>
<input matInput maxlength="50" type="text" placeholder="Clé Camelcase" [formControl]="cle_camelcase" title="Clé Camelcase" [(ngModel)]="code" required>
</mat-form-field>
</optimus-mat-form-field>
<optimus-mat-form-field type="input" class="optimus-mat-form-field-width-50">
<mat-form-field>
<input matInput maxlength="50" type="text" placeholder="Section" [formControl]="cle_section"
title="Section" required>
</mat-form-field>
</optimus-mat-form-field>
that's my component
export class ModificationCleComponent extends FormFieldsContainer {
toggleReadonly() {
this.isReadonly = !this.isReadonly;
}
envExploitDisabled = ["RI","RU","FOR"];
// Formulaire
cleFormGroup: FormGroup;
// Champs
cle_java: FormControl;
cle_camelcase: FormControl;
cle_type: FormControl;
cle_section: FormControl;
cle_desc: FormControl;
cle_active: FormControl;
code:String ;
// Environnements
valeursControls: { valeur: valeurReferentiel, formControl: FormControl }[] = [];
// Modèle
cleReferentiel: CleReferentiel;
// Constructeur
constructor(public dialogRef: MatDialogRef<ModificationCleComponent>, private fb: FormBuilder, changeDetectorRef: ChangeDetectorRef,
private administrationService: AdministrationService, #Inject(MAT_DIALOG_DATA) cleReferentiel: CleReferentiel, public habilitationService: HabilitationService) {
super(changeDetectorRef);
this.cleReferentiel = cleReferentiel ? cleReferentiel : { cle_id: null, cle_java: null, cle_camelcase: null,
cle_section: null, cle_desc: null, cle_type: null, cle_active: true, cle_flag: false }; //cle active par defaut
this.buildForm();
// Binding
this.setUpdateModel(this.cleReferentiel);
}
// Méthode cycle de vie
ngOnInit() {
}
in this code I have communication between two text area with NGMODEL, but I want to do some modification on the input value as I showed on the picture below
result wish
Related
I've created a little Fiddle to illustrate the issue: https://stackblitz.com/edit/react-avejvc-mmhqda?file=index.js
This form works:
<Form initialValues={{ surname: 'Mouse'}}>
<Form.Item name="surname">
<Input />
</Form.Item>
</Form>
This form doesn't:
<Form initialValues={{ surname: 'Mouse'}}>
<Form.Item name="surname">
<Input />
{null}
</Form.Item>
</Form>
The only difference is that the Form.Item in the second form has two children.
Is there an intention behind this?
In case anyone wonders why I am asking. So sth like this is breaking the form:
<Form.Item name={name}>
{type==="string" && <Input />}
{type==="integer" && <InputNumber />}
</Form.Item>
The official documentation here gives examples of using multiple children in one Form.Item.
<Form.Item label="Field">
<Form.Item name="field" noStyle><Input /></Form.Item> // that will bind input
<span>description</span>
</Form.Item>
You appear to have a problem with what you are putting in the Form.Item, ie. {null} may not be allowed.
I found a solution and have a better understanding now of what is going on.
From the docs (https://ant.design/components/form/#Form.Item):
After wrapped by Form.Item with name property, value(or other property defined by valuePropName) onChange(or other property defined by trigger) props will be added to form controls, the flow of form data will be handled by Form
There is a working example in the docs too, here is the codepen: https://codepen.io/pen?&editors=001
const { useState } = React;;
const { Form, Input, Select, Button } = antd;
const { Option } = Select;
const PriceInput = ({ value = {}, onChange }) => {
const [number, setNumber] = useState(0);
const [currency, setCurrency] = useState('rmb');
const triggerChange = (changedValue) => {
onChange?.({
number,
currency,
...value,
...changedValue,
});
};
const onNumberChange = (e) => {
const newNumber = parseInt(e.target.value || '0', 10);
if (Number.isNaN(number)) {
return;
}
if (!('number' in value)) {
setNumber(newNumber);
}
triggerChange({
number: newNumber,
});
};
const onCurrencyChange = (newCurrency) => {
if (!('currency' in value)) {
setCurrency(newCurrency);
}
triggerChange({
currency: newCurrency,
});
};
return (
<span>
<Input
type="text"
value={value.number || number}
onChange={onNumberChange}
style={{
width: 100,
}}
/>
<Select
value={value.currency || currency}
style={{
width: 80,
margin: '0 8px',
}}
onChange={onCurrencyChange}
>
<Option value="rmb">RMB</Option>
<Option value="dollar">Dollar</Option>
</Select>
</span>
);
};
const Demo = () => {
const onFinish = (values) => {
console.log('Received values from form: ', values);
};
const checkPrice = (_, value) => {
if (value.number > 0) {
return Promise.resolve();
}
return Promise.reject(new Error('Price must be greater than zero!'));
};
return (
<Form
name="customized_form_controls"
layout="inline"
onFinish={onFinish}
initialValues={{
price: {
number: 0,
currency: 'rmb',
},
}}
>
<Form.Item
name="price"
label="Price"
rules={[
{
validator: checkPrice,
},
]}
>
<PriceInput />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
);
};
ReactDOM.render(<Demo />, mountNode);
I used react typescript project to ant design and i used this ant design form validation, but its not working correctly, anyone know how to fix that issue?
Thanks
git a this error
index.tsx?789d:32 Uncaught TypeError: Cannot read property
'getFieldDecorator' of undefined
import * as React from "react";
import { Input, Form, Icon, Button, } from "antd";
import 'antd/dist/antd.css';
import "./style.css";
export class Registerform extends React.Component<any> {
handleSubmit = (e:any) => {
e.preventDefault();
this.props.form.validateFieldsAndScroll((err:any, values:any) => {
if (!err) {
console.log('Received values of form: ', values);
}
});
};
render() {
const { getFieldDecorator } = this.props.form;
return (
/* Start add bulk upload form*/
<div className="remindersform-section">
<Form onSubmit={this.handleSubmit}>
<Form.Item
label={
<span>
Nickname
<Icon type="question-circle-o" />
</span>
}
>
{getFieldDecorator('nickname', {
rules: [{ required: true, message: 'Please input your nickname!', whitespace: true }],
})(<Input />)}
</Form.Item>
<Form.Item >
<Button type="primary" htmlType="submit">
Register
</Button>
</Form.Item>
</Form>
</div>
);
}
}
Because default form props are not assigned with their types, antd provided a solution for it, Try like below
import * as React from "react";
import { FormComponentProps } from "antd/es/form";
import { Input, Form, Icon, Button, } from "antd";
import 'antd/dist/antd.css';
interface UserFormProps extends FormComponentProps {
form: any;
}
class Registerform extends React.Component<UserFormProps> {
handleSubmit = (e:any) => {
e.preventDefault();
this.props.form.validateFieldsAndScroll((err:any, values:any) => {
if (!err) {
console.log('Received values of form: ', values);
}
});
};
render() {
const { getFieldDecorator } = this.props.form;
return (
/* Start add bulk upload form*/
<div className="remindersform-section">
<Form onSubmit={this.handleSubmit}>
<Form.Item
label={
<span>
Nickname
<Icon type="question-circle-o" />
</span>
}
>
{getFieldDecorator('nickname', {
rules: [{ required: true, message: 'Please input your nickname!', whitespace: true }],
})(<Input />)}
</Form.Item>
<Form.Item >
<Button type="primary" htmlType="submit">
Register
</Button>
</Form.Item>
</Form>
</div>
);
}
}
const WrappedForm = Form.create<UserFormProps>({})(Registerform);
export default WrappedForm;
<div class="example-container">
<div class="pb-16" fxLayout="row" fxLayoutAlign="start center">
<div class="h2 secondary-text">
<b>
<u>Profile Details of {{rows ? rows?.categoryName : ''}}</u>
</b>
</div>
</div>
<br />
<mat-form-field>
<mat-label>Category Name</mat-label>
<input matInput placeholder="category name" value="{{rows ? rows?.categoryName : ''}}">
</mat-form-field>
<br />
<br />
<mat-form-field class="example-full-width">
<mat-label>Category Description</mat-label>
<textarea matInput placeholder="category description" value="{{rows ? rows?.categoryDesc : ''}}"></textarea>
</mat-form-field>
</div>
This is component.html
import { Component,OnInit,Input } from "#angular/core";
import { MatSnackBar } from '#angular/material';
import { coerceBooleanProperty } from "#angular/cdk/coercion";
import { HttpClient } from "#angular/common/http";
import { ActivatedRoute } from "#angular/router";
import { FormBuilder, FormGroup, Validators,FormControl } from
'#angular/forms';
import { Location} from '#angular/common';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/delay';
import 'rxjs/add/operator/map';
import {ServiceContactsFakeDb} from '../../../../../fuse-fake-db/service-
contacts';
import { Data } from '../../../../../fuse-fake-db/hero';
import { LIST } from '../../../../../fuse-fake-db/mock-heroes';
import {CategoryService} from "../category.service";
#Component({
selector: 'profile-detail',
templateUrl: './profile.component.html',
styleUrls:['./component.scss'],
providers:[CategoryService]
})
export class ProfileComponent implements OnInit {
constructor (private location:Location,private http: HttpClient,private
service:CategoryService,private _Activatedroute:ActivatedRoute){
}
name = new FormControl('', [Validators.required]);
name1 = new FormControl('', [Validators.required]);
favoriteSeason: any;
_card = false;
profiles = LIST;
#Input() category;
selectedProfile: Data;
rawdata:any[];
rows: any[];
reorderable = true;
categoryName : any[];
categoryDesc : any = {};
data = [];
item:string[];
id:string;
catName: string;
catDesc: string;
//selectedProfile: ServiceContactsFakeDb;
setDataLayoutType(value: boolean) {
this._card = coerceBooleanProperty(value);
}
ngOnInit(){
// this.getDetail();
this.id=this._Activatedroute.snapshot.params['id'];
console.log(this.id);
this.service.getcategory().subscribe(res => {
this.rawdata = res;
for(var i=0;i<this.rawdata.length;i++){
if(this.id == this.rawdata[i].id){
this.rows=this.rawdata[i];
console.log(this.rows);
}
}
});
}
In this code I am getting error in component.html file like this :
[Angular] Identifier 'categoryName' is not defined. 'Array' does not contain such a member .
I am fetching the values from an api, I am getting the output but still it shows errors in this line "value="{{rows ? rows?.categoryName : ''}}"
I had defined rows as a array replace it with rows: any={} instead of rows: any[];
I need to get value of a certain input in my dynamic form.
I have JSON parameters like this
{
"etiquette":"Téléphone mobile",
"ordre":1,
"obligatoire":true,
"pattern":"^(?:(?:(?:\\\\+|00)33[ ]?(?:\\\\(0\\\\)[ ]?)?)|0){1}[1-9]{1}([ .-]?)(?:\\\\d{2}\\\\1?){3}\\\\d{2}$",
"section":"TelMail",
"type":"text",
"nom":"telephoneMobile",
"texteIndice":"Téléphone mobile"
}
,
{
"etiquette":"Mail",
"ordre":2,
"obligatoire":true,
"pattern":"(?:[a-zA-Z0-9!#$%&''*+=?^_`{|}~-]+(?:\\\\.[a-zA-Z0-9!#$%&''*+=?^_`{|}~-]+)*|\u201d(?:[\\\\x01-\\\\x08\\\\x0b\\\\x0c\\\\x0e-\\\\x1f\\\\x21\\\\x23-\\\\x5b\\\\x5d-\\\\x7f]|\\\\\\\\[\\\\x01-\\\\x09\\\\x0b\\\\x0c\\\\x0e-\\\\x7f])*\u201d)#(?:(?:[a-zA-Z0-9àâäçéèëêîïôôûüù](?:[a-zA-Z0-9-àâäçéèëêîïôôûüù]*[a-zA-Z0-9àâäçéèëêîïôôûüù])?\\\\.)+[a-zA-Z0-9àâäçéèëêîïôôûüù](?:[a-zA-Z0-9-àâäçéèëêîïôôûüù]*[a-zA-Z0-9àâäçéèëêîïôôûüù])?|\\\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-zA-Z0-9-]*[a-zA-Z0-9]:(?:[\\\\x01-\\\\x08\\\\x0b\\\\x0c\\\\x0e-\\\\x1f\\\\x21-\\\\x5a\\\\x53-\\\\x7f]|\\\\\\\\[\\\\x01-\\\\x09\\\\x0b\\\\x0c\\\\x0e-\\\\x7f])+)\\\\])",
"section":"TelMail",
"type":"email",
"nom":"mail",
"texteIndice":"Mail"
},
{
"etiquette":"Type alerte",
"ordre":3,
"obligatoire":true,
"options": [{
"code" : "SMS",
"valeur" : "Alertes SMS"
},
{
"code" : "MAIL",
"valeur" : "Alertes Mail"
}],
"section":"Alerte",
"type":"radio",
"nom":"typeAlerte",
"texteIndice":"Type alerte"
}
I have Interface like below screenshot.
I customised radio component to contain radio input and input for mail and phone.
What I need is: get value of input phone/mail and put in in the input related to the radio.
Here is my radio component:
import {Component,Inject,Input} from '#angular/core';
import {NgForm, FormGroup} from '#angular/forms';
import {ExtraFormField} from '../model/form';
import {ExtraField} from './extra-field';
import { CatalogueService } from "../../catalogue/catalogue.service";
#Component({
selector: 'radio-extra-field',
template:`
<div class="form-group" >
<label [attr.for]="field.nom">{{field.etiquette}}</label>
<div *ngFor="let option of field.options" >
<input type="radio" name ="{{field.nom}}" value="{{option.code}}" id="{{option.code}}" [(ngModel)]="typeSelectionne">{{option.valeur}}
<input id="{{option.code}}" [attr.title]="field.etiquette" [attr.minlength]="field.longueurMin" [attr.min]="field.min" [attr.max]="field.max"
[attr.maxlength]="field.longueurMax" [attr.value]="field.valeur"
[attr.type]="text" [formControl]="fieldControl" (change)="maj(id.value)"
[attr.id]="option.code" type="text" [attr.disabled]="typeSelectionne != option.code? disabled : null ">
<error-messages [control]="field.nom"></error-messages>
</div>
<error-messages [control]="field.nom"></error-messages>
</div>
`
})
export class RadioExtraField extends ExtraField {
typeSelectionne: string;
#Input() field:ExtraFormField;
#Input() entity:{fields:Object};
#Input() formGroup:FormGroup;
constructor(public catalogueService: CatalogueService, #Inject(NgForm) formDir: NgForm) {
super(null, catalogueService, formDir);
}
get disabled():string {
if(this.field) {
return 'disabled';
}
return null;
}
}
Is there a way to do this ?
thank you
You can use
(ngModelChange)
what it do is it will call function ,there you can assign value to ngModel of input field.
What am I missing here? I'm trying to pass 2 fields(CustomerID and CompanyName) from my view into my controller. When I put a break point on my controller's action, both custID and Company name are null. I'm sure whatever I'm missing is easy but I'm just not getting into Angular. Any help would be greatly appreciated. Thanks!
HTML
<input type="text" class="form-control" ng-model="new.CustomerID" />
<input type="text" class="form-control" ng-model="new.CompanyName" />
Javascript
$scope.AddCustomer = function () {
debugger;
var urlPost = "/Home/SaveCustomer/";
console.log($scope.new);
alert(urlPost);
$http({
method: 'POST',
url: urlPost,
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
data: { custID: $scope.new.CustomerID, CompanyName: $scope.new.CompanyName }
}).success(function() {
alert('Update Successfully!');
});
}
C#
[HttpPost]
public void SaveCustomer(string custID, string CompanyName)
{
}
EDIT
A few weeks after this was posted and an answer was accepted, I found an easier way to accomplish this. Here is a code sample:
HTML
<input type="number" placeholder="CustomerID" ng-model="newCustomer.CustomerID" class="form-control" style="width: 130px" required/>
<input type="text" placeholder="Customer Name" ng-model="newCustomer.CustomerName" class="form-control" style="width: 200px" required />
<input type="text" placeholder="Email" ng-model="newCustomer.CustomerEmail" class="form-control" style="width: 200px" required />
JavaScript
$scope.newCustomer = {
CustomerID: '',
CustomerName: '',
CustomerEmail: ''
};
$scope.addCustomer = function () {
$http.post("/Home/GetCustomer",
{
customerID: $scope.newCustomer.CustomerID,
customerName: $scope.newCustomer.CustomerName,
customerEmail: $scope.newCustomer.CustomerEmail
}).error(function (responseData) {
alert(responseData);
})
.success(function () {
alert('Updated Successfully');
});
C# Controller
[HttpPost]
public void GetCustomer(int customerID, string customerName, string customerEmail)
{
//do something with values
}
I mean your problem is because the binding that web api uses there is base on querystring, so please update your code, I do an example:
public class UsersController : ApiController
{
[HttpPost]
[Route("Users/Save/{custID}/{CompanyName}")]
public string Save(string custID, string CompanyName)
{
return string.Format("{0}-{1}",custID, CompanyName);
}
}
And the html:
<body ng-app="myApp">
<div ng-controller="myController">
<h1>Demo</h1>
<input type="button" value="Save" ng-click="AddCustomer()" />
</div>
<script src="~/Scripts/angular.js"></script>
<script>
var app = angular.module("myApp", []);
app.controller("myController", function($scope, $http) {
$scope.new = {
CustomerID: "CustId1",
CompanyName: "Company 1"
}
$scope.AddCustomer = function () {
var urlPost = "/Users/Save/" + $scope.new.CustomerID + "/" + $scope.new.CompanyName
$http({
method: 'POST',
url: urlPost,
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function () {
alert('Update Successfully!');
});
}
});
</script>
</body>
And if I test:
Regards,
make these changes :
//either define parent object scope only
$scope.new = {}
//or if you want to define child object too . May be to show some default value .
$scope.new = {
CustomerID: '', //empty or may be some default value
CompanyName: ''
}