How to set role on the registration form programmatically
You need to do this in a form alter hook, not after the form has already been built.
function module_form_user_form_alter(array &amp;$form, FormStateInterface $form_state, $form_id) {
  if ($condition) {
    $form['account']['roles']['#default_value'][] = 'mycustomrole';
  }
}