当我们将鼠标悬停在表格的第一列上时,将显示一个工具提示,然后单击工具提示垫对话框中的按钮presnt即可打开。
对话框包含2个部分以及Edit json和。在左侧选择的那一行,其对应的数据在右侧显示为json。
1)基本表单验证有效,但我需要显示一些消息(如果表单无效),以防用户编辑json并尝试单击按钮。 (尝试使用模糊[ngModelOption] [ngFormOption] onUpdate属性,但无法实现)
对于json部分以及基本验证也有效,但对于以下几点,如何提供验证:
1)如果我将键设为空字符串,则无法验证。
2)如何使特定密钥为必填项。
Stackblitz链接 https://stackblitz.com/edit/angular-mat-tooltip-qxxgcp?file=app%2Falert-dialog%2Falert-dialog.component.html
alert-dialog.component.ts的摘录
<form #jsonform="ngForm" (ngSubmit)="onAddNewAlert()">
<json-input [(ngModel)]="data.data[incomingSelectedAlert].conditionals" name="result"></json-input>
<button type="submit" class="btn btn-success alertButtonSubmit" [disabled]="jsonform.invalid">Add As New Alert</button>
</form>
json-input.component (我有NG_VALIDATORS和valdidate函数执行基本的json验证)
@Component({
selector: 'json-input',
template:
`
<style>
textarea {
height: 421px;
width: 480px;
resize: none;
}
</style>
<textarea
[value]="jsonString"
(change)="onChange($event)"
(keyup)="onChange($event)">
</textarea>
`,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => JsonInputComponent),
multi: true,
},
{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => JsonInputComponent),
multi: true,
}]
})
export class JsonInputComponent implements ControlValueAccessor, Validator {
private jsonString: string;
private parseError: boolean;
private data: any;
// this is the initial value set to the component
public writeValue(obj: any) {
if (obj) {
this.data = obj;
// this will format it with 4 character spacing
this.jsonString = JSON.stringify(this.data, undefined, 4);
}
}
// registers 'fn' that will be fired wheb changes are made
// this is how we emit the changes back to the form
public registerOnChange(fn: any) {
this.propagateChange = fn;
}
// validates the form, returns null when valid else the validation object
// in this case we're checking if the json parsing has passed or failed from the onChange method
public validate(c: FormControl) {
return (!this.parseError) ? null : {
jsonParseError: {
valid: false,
},
};
}
// not used, used for touch input
public registerOnTouched() { }
// change events from the textarea
private onChange(event) {
// get value from text area
let newValue = event.target.value;
try {
// parse it to json
this.data = JSON.parse(newValue);
this.parseError = false;
} catch (ex) {
// set parse error if it fails
this.parseError = true;
}
// update the form
this.propagateChange(this.data);
}
// the method set in registerOnChange to emit changes back to the form
private propagateChange = (_: any) => { };
}
答案 0 :(得分:1)
我已通过以下步骤完成了您需要做的事情:
NgForm
指令不是一个好习惯)向forbiddenFields
mandatoryFields
(由于它是JS中的实际有效键,所以包含空字符串)和JsonInputComponent
。
mandatoryFields: string[] = ["conditionals", "offset", "alert"];
forbiddenFields: string[] = [""];
在onChange
函数中执行字段检查:
private onChange(event) {
// get value from text area
let newValue = event.target.value;
try {
// parse it to json
this.data = JSON.parse(newValue);
const datakeys = Object.keys(this.data);
const containsForbiddenFields = datakeys.some(x => this.forbiddenFields.indexOf(x) >= 0);
const containsMandatoryFields = this.mandatoryFields.every(x => datakeys.indexOf(x) >= 0);
this.parseError = containsForbiddenFields || !containsMandatoryFields;
} catch (ex) {
// set parse error if it fails
this.parseError = true;
}
// update the form
this.propagateChange(this.data);
}
有关完整的工作解决方案,这是分叉的Stackblitz
答案 1 :(得分:1)
我已按照以下步骤操作,并根据要求更新了您的代码,它似乎运行良好:
用于添加验证以检查中的空字符串和必需键 嵌套对象时,我在ngOnInit()方法上添加了逻辑值 控件值的帮助下AlertDialogComponent中的表单更改 访问器。
添加了这些变量以验证表单并获取JSON对象的密钥,
isFormValid = true;
mandatoryField = ['conditionals', 'offset', 'alert', 'mTitle'];
allMandatoryFieldsExists: boolean;
在此处附加我的解决方案和主要代码,Stackblitz
this.jsonform.statusChanges.subscribe(() => {
let data = this.jsonform.value.result;
let keys = [];
if(data) {
for(var i in data) {
keys.push(i);
if(i === 'offset' && data[i] === '') {
this.isFormValid = false;
return;
} else {
this.isFormValid = true;
}
if(i === 'conditionals') {
for(var j in data[i][0]) {
keys.push(j);
if(data[i][0][j] === '') {
this.isFormValid = false;
return;
} else {
this.isFormValid = true;
}
}
}
if(i === 'alert') {
for(var j in data[i]) {
keys.push(j);
if(data[i][j] === '') {
this.isFormValid = false;
return;
} else {
this.isFormValid = true;
}
}
}
}
this.allMandatoryFieldsExists = this.mandatoryField.every(x => keys.indexOf(x) >= 0);
}
if(this.jsonform.dirty && (!this.isFormValid || !this.allMandatoryFieldsExists)){
console.log("form is dirty and not valid")
// this.alertService.error("Json not correct. Please fix!");
}else{
console.log("form is dirty but valid")
}
});