Skip to content

Instantly share code, notes, and snippets.

@2n2n
Last active September 21, 2017 12:05
Show Gist options
  • Save 2n2n/68222531d9d27843969df1d104da3ff0 to your computer and use it in GitHub Desktop.
Save 2n2n/68222531d9d27843969df1d104da3ff0 to your computer and use it in GitHub Desktop.
// imports..
@Component({
// same same ...
})
export class MyComponent implements OnInit {
public form: FormGroup;
constructor(private config: MyService) {}
ngOnInit() {
this.config.init();
this.form = this.config.form.general;
}
// update form
update() {
let formdata = [];
Object.keys(this.form.value).forEach(k => {
// ibabalik ko parse to decimal
if(k == 'field1') { this.form.value[k] = this.form.value[k] / 100 }
formdata.push({slug: k, value: this.form.value[k]})
});
// Eto yung medyo special na part. kasi di ko alam kung okay ba na practice tong pag pasa
// ng callback sa function ng service.
this.config.update(formdata, res => {
alert(res.message);
});
}
}
<form [formGroup]="form" (ngSubmit)="update()">
<div class="row">
<div class="form-group col-md-3">
<label>Field1:</label>
<input
formControlName="field1"
type="text" class="form-control">
</div>
</div>
<button type="submit" class="btn btn-warning">Update Changes</button>
</form>
// imports ...
@Injectable()
export class MyService {
constructor(private http: Http) { }
public form = {
general: new FormGroup({
"field1": new FormControl(0, Validators.required)
})
};
init() {
this.getAll()
.subscribe(data => {
data.forEach(row => {
// kung field1 ang nakuha na row gagawin kong whole number ang value.
if( row.slug == 'field1') { row.value = row.value * 100 }
this.form.general.get(row.slug).setValue(row.value);
});
});
}
// get values from server. e.g response [{slug: 'field1', value: '.2'}]
getAll() {
return this.http.get('/v1/url')
.map(res => res.json());
}
//update given callback.
// callback is for the subscribe function.
update(formdata, callback) {
return this.http
.put('v1/url/update', {data: formdata})
.map(res => res.json())
.subscribe(callback) // dito ko tinawag si callback
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment